为什么鼠标的坐标会出现在鼠标之外的其他地方?

时间:2019-08-22 15:59:54

标签: javascript html canvas

我试图这样做,当您单击画布时,鼠标的坐标上会出现一个圆圈。 当我单击画布时,圆圈可能会变低300像素。

我尝试从pageX / Y,clientX / Y和screenX / Y更改。

<canvas id="canvas" class="canvas" width="300px" height="200px" style="border: 1px solid #000; Padding-bottom: 100px;">
</canvas>
<script>
        window.onload = function()
        {
            var canvas = document.getElementById("canvas");
            addEventListener("mousedown", drawCircle)
        }

        function drawCircle(event) 
        {
            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");

            x = event.pageX
            y = event.pageY

            ctx.fillStyle = "red";
            ctx.beginPath();
            ctx.arc(x, y, 50, 0, 2 * Math.PI);
            ctx.stroke();
            ctx.fill()
        } 
</script> 

我希望圆会出现在鼠标的坐标上。

3 个答案:

答案 0 :(得分:1)

您需要考虑画布本身的位置。看起来您的代码假定画布始终位于屏幕的左上方。

您的canvas元素也存在一些问题。宽度和高度应该只是数字(不需要“ px”)。底部的填充物使画布的下半部分无法访问。

window.onload = function() {
  var canvas = document.getElementById("canvas");
  addEventListener("mousedown", drawCircle)
}

function drawCircle(event) {
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");

  var rect = canvas.getBoundingClientRect();
  x = event.clientX - rect.left;
  y = event.clientY - rect.top;

  ctx.fillStyle = "red";
  ctx.beginPath();
  ctx.arc(x, y, 50, 0, 2 * Math.PI, true);
  ctx.stroke();
  ctx.fill()
}
<canvas id="canvas" class="canvas" width="300" height="200" style="border: 1px solid #000;">
</canvas>

答案 1 :(得分:0)

可能被画布上页面上的其他元素偏移。尝试这样的操作以相对于画布获得x / y:

<canvas id="canvas" class="canvas"></canvas>
<script>
  window.onload = function () {
    var canvas = document.getElementById("canvas");
    canvas.width = 300;
    canvas.height = 200;
    addEventListener("mousedown", drawCircle)
  }

  function drawCircle(event) {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    var rect = canvas.getBoundingClientRect();
    x = (event.clientX - rect.left)
    y = (event.clientY - rect.top)

    //x = event.pageX
    //y = event.pageY

    ctx.fillStyle = "red";
    ctx.beginPath();
    ctx.arc(x, y, 50, 0, 2 * Math.PI);
    ctx.stroke();
    ctx.fill()
  } 
</script> 

答案 2 :(得分:0)