Mouse Coordinates on Canvas after CSS scale

前端 未结 1 951
隐瞒了意图╮
隐瞒了意图╮ 2021-01-25 15:39

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. W

相关标签:
1条回答
  • 2021-01-25 16:25

    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:

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

    as shown in this example:

    var canvas = document.createElement("canvas");
      document.body.appendChild(canvas);
      canvas.width = 700;
      canvas.height = 700;
    var ctx = canvas.getContext("2d");    
    
    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");
    
      // scale mouse coordinates to canvas coordinates
      var canvasX = mouseX * canvas.width / canvas.clientWidth;
      var 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>

    0 讨论(0)
提交回复
热议问题