Mouse Coordinates on Canvas after CSS scale

前端 未结 1 781
南笙
南笙 2021-01-25 15:48

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条回答
  •  萌比男神i
    2021-01-25 16:26

    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+"
    "+canvasX+" | "+canvasY; });
    canvas {
      width:250px;
      height:250px;
      background-color:#f0f;
    }
    ??? | ???
    ??? | ???

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