The position of the mouse on the canvas following a CSS scaling

I'm currently working on finding the mouse coordinates on an HTML5 canvas element.

I set the canvas dimensions to 700x700. When I hover over the canvas, I aim to retrieve the X,Y coordinates of the mouse. Everything goes smoothly until I resize the canvas using CSS in the HTML file...

Check out my JavaScript file: function Sprite(path) { this.img = new Image(); this.img.onload = loaded; this.img.src = path;

    function loaded()
    {
        console.log("Image loaded successfully");
    }
}

function drawSprite(sprite, ctx)
{
    console.log("Drawing image");
    ctx.drawImage(sprite.img, 10, 10);
}

//------------------------------------------

function Game()
{
    this.canvas = document.createElement("canvas");
    document.body.appendChild(this.canvas);
    this.canvas.width = 700;
    this.canvas.height = 700;
    this.context = this.canvas.getContext("2d");    

    var ctx = this.context;

    ctx.canvas.addEventListener('mousemove', function(event){
        var mouseX = event.clientX - ctx.canvas.offsetLeft;
        var mouseY = event.clientY - ctx.canvas.offsetTop;
        var status = document.getElementById("coordinates");
        status.innerHTML = mouseX + " | " + mouseY;

    });


    this.objects = new Array();
    this.objects.push(new Sprite("dog.png"));
}

function drawGame(g)
{
    console.log("Here I am");
    for(var i = 0; i < g.objects.length; i++)
    {
        drawSprite(g.objects[i], g.context);
    }
}

function drawLine(g)
{
    g.context.moveTo(0, 0);
    g.context.lineTo(100, 100);
    g.context.stroke();
}

//------------------

window.addEventListener('load', function(event){startgame();});
var globalGame;

function startgame()
{
    globalGame = new Game();
    drawGame(globalGame);
    drawLine(globalGame);
}

Take a look at my HTML File

<html>
    <head>
        <script src="functions.js"></script>
        <style>
            canvas
            {
                width: 90%;
                height: 90%;
            }
        </style>
    </head>
    <body>

    <h1 id="coordinates">0 | 0</h1>
    </body>
<html>

Answer №1

The coordinates of the mouse are based on the display pixels. If you want to convert them to canvas coordinates, you will need to scale them accordingly.

One method to achieve this is:

const canvasX = mouseX * canvas.width / canvas.clientWidth;
const canvasY = mouseY * canvas.height / canvas.clientHeight;

Here is an example to illustrate this:

const result = document.getElementById("position");

const canvas = document.createElement("canvas");
canvas.width = 800;
canvas.height = 800;
document.body.appendChild(canvas);

canvas.addEventListener('mousemove', event => {
  const mouseX = event.clientX - canvas.offsetLeft;
  const mouseY = event.clientY - canvas.offsetTop;

  // converting mouse coordinates to canvas coordinates
  const canvasX = mouseX * canvas.width / canvas.clientWidth;
  const canvasY = mouseY * canvas.height / canvas.clientHeight;

  result.innerHTML = `${mouseX} | ${mouseY}<br>${canvasX} | ${canvasY}`;
});
canvas {
  width:300px;
  height:300px;
  background-color:#ccc;
}
<div id="position">??? | ???<br>??? | ???</div>

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

Staggered Drop-Down Menus

I've created a custom CSS drop-down menu that works well, but I've realized that updating this menu across all the HTML pages on my website would be a tedious task. If I ever need to add a new section and tier to the menu, I'd have to update ...

The server tag is displaying an error due to incorrect formatting in the hyperlink data-binding section

I'm currently facing an issue with the formatting of my hyperlink. The text part of the hyperlink is working fine, which leads me to believe that the problem lies within the JavaScript. However, I am unable to pinpoint the exact issue. <asp:Templa ...

Generate captivating background visuals with animated elements that evolve over time

I need help creating a dynamic background image that transitions smoothly every few seconds. The current code I have doesn't include animation, and the images are taking too long to load. Is there a way to optimize the loading time? Here's my ex ...

What is the best way to dynamically resize a div as the page size changes?

I am currently working on a project that involves a div dynamically shrinking as the page size decreases. However, I have encountered an issue where the height of the div remains constant despite this resizing: CSS .container { min-height: 180px; max ...

What exactly is the significance of "utilizing a universal class name"?

In my current project, I am utilizing Material-UI version 3.1.2 to create the interface. Previously, when I was using Bootstrap4, I included style="overflow-y: scroll; height: 100%" in my head tag to ensure a scrollbar is always present, preventing the ap ...

Optimizing Material UI Themes: Adjusting the spacing between labels and inputs for improved design

Currently, I am in the process of updating my MUI themes using the overrides functionality. This is how my input field looks like: https://i.sstatic.net/OFAGf.png I am looking to increase the space between the label and the input field. Below is the co ...

Is there a way to trigger validation with a disabled property?

My form element is set up like this: <input type="text" id="country" formControlName="Country" /> The form group looks like this: this.myForm = this.formbuilder.group({ 'Country': [{ value: this.user.Country, disabled: this.SomeProperty= ...

Assistance needed with CSS selectors for implementing with selenium

<div id="footerSearchInputDefault" class="defaultText" style="visibility: hidden;">Search myTwonky</div> In relation to selenium, what do the following terms refer to in the above code snippet? attribute element value text label I often fin ...

React with Typescript - Type discrepancies found in Third Party Library

Recently, I encountered a scenario where I had a third-party library exporting a React Component in a certain way: // Code from the third party library that I cannot alter export default class MyIcon extends React.Component { ... }; MyIcon.propTypes = { ...

The value calculated by Auto does not display as a valid number in Angular 8 until it has been manually edited

Having an issue with a form submission for invoicing. The total value field, which is auto-calculated based on quantity and unit price, does not show up as numeric data in the backend onSubmit event unless I manually interact with it by adding something ...

Sleek dialog sliding animation with Svelte

I'm struggling with a svelte component that I have and I'm trying to implement a slide down animation when it closes. The slide up animation is functioning correctly, but for some reason the slide down animation is not working. Does anyone have a ...

The project is not being recognized by 'webpack' when running within it

Every time I attempt to execute 'webpack' in my project, the command line shows me this error message: 'webpack' is not recognized as an internal or external command, operable program or batch file. I have installed webpack using th ...

Retrieving a specific attribute pair from a JSON object

Currently, I am trying to retrieve the temperature data and display it on my webpage. Since these are objects with no specific order, I am struggling to understand how to access them without using an index. { "response": { "version": "0.1", "termsofServic ...

.htaccess file is causing js and css files to not load

I followed an MVC tutorial by howcode on YouTube, but I encountered an issue where my CSS and JS files were not loading due to the htaccess configuration. .htaccess file: RewriteEngine On RewriteRule ^([^/]+)/? index.php?url=$1 [L,QSA] I attempted vario ...

Ways to split a string using jQuery

I am working with a jQuery string array that contains the following elements: ["$1#Structure$2#Accounting$3Acc#$1Programming"] My task is to split the strings after the '#' symbol and provide the following result: ["Structure","Accounting","Ac ...

The ReactJS input box is stubbornly rejecting all input

Struggling with this code and can't seem to figure out why the input lines aren't accepting anything. After searching extensively, I decided it was time to ask for help. P.S. I am new to react class App extends React.Component { state = { inp ...

Users are reporting a problem with the PrimeNG confirmation dialog where it becomes unresponsive and locks up the screen

Previously functioning code seems to have been affected by an update to PrimeNG. The confirmation dialog that was once usable is now hidden behind a gray click-mask, rendering everything on the screen unclickable: https://i.sstatic.net/YN7Iu.png The HTML ...

Is there a way to store mathematical equations in a database efficiently?

My website is built in Asp.net and I am utilizing MySql as my database. I have several sample math papers saved in Microsoft Office Word format. What I need is an HTML input tool, such as a textbox or editor, that will allow me to directly copy mathematica ...

The pause option in urql's useQuery function offers a temporary halt to the request and does not freeze it completely

I'm attempting to ensure that the urql useQuery function is only executed once in my code. Unfortunately, it seems to be getting called on every re-render. According to the documentation at , this query should start off paused when rendered and shoul ...

rotate a game embedded in a website by 90 degrees

Need assistance in rotating this embed code by 90 degrees. Can you provide some guidance? <div class="miniclip-game-embed" data-game-name="8-ball-pool-multiplayer" data-theme="0" data-width="750" data-height="520" data-language="en"><a href="http ...