1

I am attempting to locate the coordinates of the mouse on a canvas element of an HTML5 page.

I create the canvas to be a certain height and width, for example 700x700. When I mouse over the canvas, I want to be able to know the X,Y of the mouse. This works fine, until I stretch my canvas using CSS in the HTML file...

Here is my javascript file: function Sprite(path) { this.img = new Image(); this.img.onload = loaded; this.img.src = path;

    function loaded()
    {
        console.log("Loaded picture");
    }
}

function drawSprite(sprite, ctx)
{
    console.log("drawing picture");
    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("coords");
        status.innerHTML = mouseX+" | "+mouseY;

    });


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

function drawGame(g)
{
    console.log("I'm here");
    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);
}

Here is my HTML File

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

    <h1 id="coords">0 | 0</h1>
    </body>
<html>
Matthew
  • 3,886
  • 7
  • 47
  • 84
  • Possible duplicate of [How to get Mouse Position on Transformed HTML5 Canvas](http://stackoverflow.com/questions/40600192/how-to-get-mouse-position-on-transformed-html5-canvas) – Kaiido Nov 22 '16 at 22:57

1 Answers1

6

The mouse coordinates are in display pixels. To convert that to canvas coordinates, you'll need to scale them accordingly.

One way of doing this is:

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

as shown in this example:

const status = document.getElementById("coords");

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

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

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

  status.innerHTML = `${mouseX} | ${mouseY}<br>${canvasX} | ${canvasY}`;
});
canvas {
  width:250px;
  height:250px;
  background-color:#f0f;
}
<div id="coords">??? | ???<br>??? | ???</div>
Ouroborus
  • 16,237
  • 4
  • 39
  • 62
  • I tried your solution but mouseX,/Y always equal to canvasX/Y after scaling of my canvas. What could be the reason? – Zvi Sep 26 '22 at 22:08
  • @Zvi You should post a new question so we can get the details needed to help answer it. – Ouroborus Sep 27 '22 at 01:12
  • I understand but since it is an old post I will continue looking for another solution – Zvi Sep 27 '22 at 06:31