When it comes to HTML and Javascript drawing, getting the positioning just right can be a challenge

I'm currently developing a control website for a drawing robot as part of a school project. However, I've been facing some challenges with the functionality of the drawing feature.

Though I admit that the site lacks attention to detail, my main focus is on getting the drawing function to work correctly.

One issue I've encountered is JavaScript not recognizing the HTML elements unless I manually call the function again using a button or an onload="" function.

My background is primarily in JAVA, and I haven't had formal training in JavaScript, HTML, or CSS design, so I kindly ask not to be judged based on that.

Initially, I suspected that the canvasOffsetx and y values were not obtaining absolute positions but relative ones from the parent div, resulting in incorrect drawings. Unfortunately, I'm unsure how to resolve this without disrupting the entire CSS layout.

The area of concern lies within the "actions" div; the remaining content is unrelated to the issue at hand.

To access the full codebase, please visit the following GitHub repository: https://github.com/Masaslo/StackOverflowQuestions.git

Answer №1

Indeed, the positioning of canvasOffsetX and Y is in relation to its parent element. It is crucial not to mismatch the canvas style and size settings as this could lead to image distortion. Adjustments must also be made when calculating the drawing position. The drawing algorithm must be revised accordingly.

To correct this, remove the styling from the canvas tag in the HTML:

- <canvas id="drawing-board" style="width: 502px; height: 502px;"></canvas>
+ <canvas id="drawing-board"></canvas>

The corrected version of the canvasFunction:

function canvasFunction(){
    const canvas = document.getElementById('drawing-board');
    const toolbar = document.getElementById('toolbar');
    const ctx = canvas.getContext('2d');
    
    const canvasOffsetX = canvas.getBoundingClientRect().left;
    const canvasOffsetY = canvas.getBoundingClientRect().top;
    
    canvas.width = window.innerWidth - canvasOffsetX;
    canvas.height = window.innerHeight - canvasOffsetY;
    
    let isPainting = false;
    let lineWidth = 5;
    let startX;
    let startY;
    
    ctx.strokeStyle = 5;
    
  
    toolbar.addEventListener('click', e => {
        if (e.target.id === 'clear') {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        }
    });
    
    
    const draw = (e) => {
        if(!isPainting) {
            return;
        }
    
        const canvasOffsetX = canvas.getBoundingClientRect().left;
        const canvasOffsetY = canvas.getBoundingClientRect().top;

        ctx.lineWidth = lineWidth;
        ctx.lineCap = 'round';
        ctx.beginPath();
        ctx.moveTo(startX - canvasOffsetX, startY - canvasOffsetY);
        ctx.lineTo(e.clientX - canvasOffsetX, e.clientY - canvasOffsetY);
        ctx.stroke();
        ctx.closePath();
        startX = e.clientX;
        startY = e.clientY;
    }
    
    canvas.addEventListener('mousedown', (e) => {
        isPainting = true;
        startX = e.clientX;
        startY = e.clientY;
    });
    
    canvas.addEventListener('mouseup', e => {
        isPainting = false;
    });
    
    canvas.addEventListener('mousemove', draw);
    
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can one integrate various angular components constructed using distinct versions of Angular?

Is it feasible to utilize various angular components (custom elements) created with different versions of Angular? I've heard concerns about zone.js causing global scope pollution. Appreciate your response! ...

Unlocking the Secret: Retrieving Click Event Values from a jQuery Function

Is there a way to retrieve the onclick event value change in jQuery when clicking on a DIV? $("ul li").click(function(){ var newValue = $(this).val(); }); $(function(){ alert(newValue); }); ...

Animating object on display and returning it with keyframes

Given the code snippet below: <div class="leftBox"> <div class="mainNode" ></div> </div> <script type="text/javascript"> $('.mainNode').click(function() { var element = $('.mainNode'); if (!ele ...

Looking for a solution to dynamically fill a list in JQuery with data from a JSON file. Any suggestions for troubleshooting?

Currently, I am utilizing a JSON file to fetch Quiz questions. In my approach, each question is being stored in an array as an object. The structure of the question object includes 'text' (the actual question), 'choices' (an array of po ...

A streamlined method for generating an array containing all numerical string values

I'm looking to generate an array of digits in JavaScript. Currently, I have hard-coded it like this: const digitGeneration = ['0', '1', '2', '3', '4', '5', '6', '7', &apo ...

Struggling to understand JSON in joint.js?

I am trying to utilize the joint.js library to render a JSON data as a chart... let paper = new joint.dia.Paper({ el: $('#paper'), width: 600, height: 200, model: graph }); let graph = new joint.dia.Graph; let json = '{"em ...

Struggling to make cookies stick in IE9

Here is the code snippet I am currently using: <script> var time = new Date(); time.setFullYear(time.getFullYear() + 1, time.getMonth(), time.getDay()); expires = ";expires=" + time.toGMTString(); document.write(expires); doc ...

Are there equivalent npm variables like (`npm_config_`) available in yarn console scripts?

Utilizing variables in custom npm commands is possible (example taken from ): { "scripts": { "demo": "echo \"Hello $npm_config_first $npm_config_last\"" } } Can this functionality also be achieved ...

Challenges Encountered When Working with Date Fields in Kendo JS Grid

We are facing an unusual issue with the Kendo UI Grid on our production site. Some users are experiencing date fields showing as null in Google Chrome, while they appear correctly in private browsing mode and other browsers like IE and MSEdge. We have bee ...

.mouseleave() triggers when exiting a designated boundary area

I'm attempting to implement a roll-up feature for a div when the mouse is over another div. The issue I'm facing is that the roll-up div closes even if the mouse just exits through the bottom border. Is there a way to achieve this using JavaScrip ...

Accessing the page directly in a Nuxt SPA is not permitted

I'm currently working with Nuxt version 2.3.4. In my project, I am utilizing vue-apollo to fetch data for a file named pages/_.vue, which dynamically manages content. As indicated on this documentation page, this is the recommended approach for handli ...

Leveraging JavaScript along with the jQuery library and API to showcase information related to

Hey there! I have been working on this API that shows upcoming concerts, but I'm struggling to display the images associated with each concert. I've tried using for loops to iterate through the objects, and it seems like every sixth element has ...

Repeating the process of running a function multiple times

export default function MyQuestions() { const router = useRouter(); const [auth, setAuth] = useState(false); const checkAuth = async () => { const loggedInUsername = await getUsername(); if (router.query.username === loggedInUsername) re ...

Exploring the complexities of object scope in Javascript

I'm having trouble accessing certain variables from a function. Here's the issue I'm facing: var PTP = function (properties) { this.errorsArray = [] } PTP.prototype.initHTMLItems = function () { $('input[data-widget-type="dat ...

Could not locate the express.js file

Currently in the process of learning express/node.js, but struggling to locate the page at localhost:3000/info You can view screenshots of my code below ...

Is it feasible to execute a cross-site request forgery attack on a URL that delivers a JSON object as a response?

I am aware of the potential for a Cross-Site Forgery Attack that can target requests returning arrays by manipulating the Array constructor. For instance, let's say I have a site with a URL: foo.com/getJson that provides the following array: [&apos ...

"Utilize the style attribute to modify the appearance based on the

I was the original asker of this question, but I failed to provide a clear description which led to not getting an answer. However, I will now explain everything here. Essentially, I am looking for a JavaScript function that can identify a class with a spe ...

Easily transfer files from your browser application to your Windows applications such as Outlook or printer queues using a simple drag and

I am attempting to transfer a downloaded file from a web browser to a Windows application (such as Outlook or a printer queue) by dragging and dropping. While I can successfully drop the file onto the desktop or any other file explorer location, I face iss ...

Sending AJAX data from VIEW to CONTROLLER in PHP (MVC) using AJAX: A step-by-step guide

I have a page at http://visiting/blog. The Controller contains two methods: action_index and add_index. When Action_index() executes, it returns pages with indexes. On the other hand, Add_index() invokes a model's method called add_data(), which inse ...

Stop SCSS from processing CSS variables in Angular-CLI

I am currently using Angular5 with sass v1.3.2. My goal is to dynamically change a color that is widely used in the scss files of my single page app without having to recompile new files. This color is globally defined in my _variables.css as: $brand: # ...