What is the best way to correct the mouse position in relation to the canvas parent?

I am currently working on incorporating the Vuejs Draw Canvas from this Codepen example into my project as a component. The functionality is all working well, but I've noticed that the mouse position seems to be relative to the window. This causes issues when the canvas is not the same size as the window, leading to discrepancies between the cursor position and the actual draw position.

I attempted to adjust the canvas width and height to be offset values rather than based on the window size, like this:

setSize() {
    this.c.width = this.c.offsetWidth;
    this.c.height = this.c.offsetHeight - 60;
}

I also tried to handle the mouse position using code from answers on Stack Overflow, such as:

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: (evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width,
        y: (evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height
    };
}

Unfortunately, these adjustments did not solve the issue. I have reverted back and created a version in a code sandbox. If anyone can assist me in identifying the problem with the mouse position, I would greatly appreciate it. I believe the issue lies in the calculations of the mouse position, but I'm unsure of the exact location.

You can find the demo I'm trying to fix in this codesandbox link.

Answer №1

Exploring two distinct methods for determining mouse location (the reason for the variance is unclear without further investigation):

canv = document.getElementById("id-of-canvas-object")

function findMouseLocation(e)
{
 if (e.preventDefault)
    e.preventDefault();
 var x = e.PageX; var y = e.PageY;
// Method one
 var relativeX = x - canv.offsetLeft;
 var relativeY = y - canv.offsetTop;
// Method two
  var rect = canv.getBoundingClientRect();
  relativeX = x - rect.left;
  relativeY = y - rect.top;
}

Answer №2

When reviewing the provided example, it appears that an unnecessary 60px offset is being subtracted during cursor repositioning due to the fixed positioning of the controls.

Two key differences can be found in lines 234 & 239:

setSize() {
  this.c.width = this.c.offsetWidth;
  this.c.height = this.c.offsetHeight; // <--- The -60px offset has been removed here
}

moveMouse(e) {
  let x = e.offsetX;
  let y = e.offsetY + 60; // <--- The 60px offset has been added here
  // The ´e.offsetY´ is relative to the canvas, but an additional offset is affecting the cursor's position

  var cursor = document.getElementById("cursor");

  cursor.style.transform = `translate(${x}px, ${y}px)`;
}

Here is the corrected example: Fixed codesandbox

Note: It is recommended to reconsider the fixed positioning of the controls and manage dimensions with fixed values or utilize flexbox for responsive canvas resizing.

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

Building a dynamic form in React: Fetching select data from an API, posting to another API, and automatically clearing fields upon submission

I am currently working on a form that utilizes a GET request to retrieve data from an API endpoint and then proceeds to make a POST request to another endpoint. Although I have been successful in achieving this function, I am facing challenges with reset ...

Adjust the text appearance of the graph in ApexCharts

Is there a way to adjust the font size of the donut chart generated by using apexchart? You can view the image here. <template> <section> <v-card raised> <v-card-title class="blue--text">Requests Overview</v-card-ti ...

Receiving time slots on a bootstrap schedule

I recently developed a calendar using Bootstrap that allows users to select a start date and automatically sets the end date within a 7-day range from the chosen start date. However, I am facing a challenge in enabling users to also pick minutes along with ...

Trigger a function when the value of the file input field changes using ng-change

I'm attempting to trigger my upload() function when the file input changes, but I'm having trouble getting it to work. This is the HTML code: <input type="file" ng-model="image" ng-change="uploadImage()"> And here's the correspondin ...

Running a JavaScript file from Docker to fill a MongoDB database is not working when using the WSL shell on Windows 10

I'm facing some issues while trying to populate my MongoDB using a script. Every time I run the script, I encounter errors even though the Docker container is up and running. For reference, I'm on Windows 10 using WSL shell. https://i.stack.img ...

Tips for designing a horseshoe-inspired meter using CSS

  I want to create a horseshoe-shaped gauge using CSS that resembles the image below:     My attempt involved creating a circle and cutting off the bottom, similar to the technique demonstrated in this fiddle: http://jsfiddle.net/Fz3Ln/12/   Here& ...

The thickness of the line on the Google line chart is starting to decrease

Currently, I am utilizing a Google line chart in my application. However, I have noticed that for the first two data points, the lineWidth is thick, while for the last two points it is very thin. How can I resolve this issue and ensure that the lineWidth r ...

Struggling to send information using Angular $resource?

I've been working on sending data to an API using Angular's $resource. Currently, I can successfully retrieve data from my test server using a GET request or querying. However, I'm having trouble figuring out how to send new data to the serv ...

Troubleshoot: Issue with Multilevel Dropdown Menu Functionality

Check out the menu at this link: The issue lies with the dropdown functionality, which is a result of WordPress's auto-generated code. Css: .menu-tophorizontalmenu-container { margin: 18px auto 21px; overflow: hidden; width: 1005px; ...

What is the best way to showcase data from input fields within a bootstrap modal dialog?

After the user has entered their details and clicks submit, I would like to present the information in a Bootstrap modal with a confirmation button below. This serves as a preview of the data before it is saved to the database. Here's what I have so ...

Error: Encountered an unexpected asterisk symbol while trying to import a Sequelize model from the

Currently, I am developing an application that requires me to connect and run queries on an SQL server using Sequelize. I have set up migrations, seeders, and models by utilizing sequelize init. However, when attempting to generate model objects with const ...

Methods for transferring data to controller in Angular Modal service

After implementing the angular modal service discussed in this article: app.service('modalService', ['$modal', function ($modal) { var modalDefaults = { backdrop: true, keyboard: true, m ...

How can I obtain the width of one element and then use it to adjust the size of another element that is

Currently, I am working on a dropdown menu and facing an issue with setting the submenus to match the width of the top-level page. In my HTML structure (specifically for a WordPress theme), it looks something like this: <ul class="menu"> <li ...

SOLVING the issue of page flicker in SVELTE

Within the application below, I am experiencing a peculiar page flicker effect that is often associated with AJAX requests. However, in this scenario, the cause is not AJAX-related but rather a conditional statement that triggers the rendering of different ...

Acquire JSON information from PHP utilizing JavaScript

I am a beginner with JSON and I'm retrieving data from PHP code in JSON format. [ { "Title": "New Event", "TYPE": "info", "StartsAt": "16 November 201512:00", "EndsAt": "25 November 201512:00" }, { ...

React encountered a 400 error when attempting to call a function in node.js

While attempting to call a registration endpoint from a React front-end to a Node.js back-end using Axios, I encountered a 400 error: http://localhost:9000/user/register 400 (Bad Request) Here is my code: /* React component for user registration */ impo ...

Is it possible to remove a form element without relying on jQuery's .remove() method?

Looking to hide the select all checkbox from users without actually removing it when submitted. The challenge lies in making the removal of the select all checkbox seamless on the front end, while ensuring it is not sent to the server. Is there a way to ...

Using Selenium to interact with a Modal Dialog window

When trying to navigate to a page in IE9 using Selenium, a certificate error message appears on the page. By using AutoIT, I am able to click within the browser, TAB twice, and hit enter without any issues. However, after this step, an error for a "Modal d ...

"Step-by-step guide on creating a dynamic clipping mask animation triggered by mouse wheel

I have developed a sample that functions just as I envision my final outcome to function, with the exception of triggering on mouse-over. Instead, I would like it to activate as a page transition when scrolling with the mouse. (move your cursor over the i ...

Adjusting the contenteditable feature to place the caret on a specific child node

I am experiencing some challenges when attempting to position the cursor after an <i> tag within a contenteditable element. Currently, this is what I have: <p contenteditable="true"><i>H</i><i>e</i><i>l</i> ...