如何在javascript中通过鼠标点击获得准确的坐标

时间:2014-12-12 09:21:37

标签: javascript html canvas mouseevent

我正在努力教自己如何在画布上点击x和y坐标来编写游戏。我写的代码有一个我无法弄清楚的微妙错误。当您单击画布时,球会大致移动到您单击的位置。但我希望它集中在我点击的位置。相反,这一点位于新球的左上角。

(我通过使用从event.clientY中返回的event.clientX和canvas.offsetTop中减去canvas.offsetLeft来编辑代码以正常工作,这两个属性在我指向类似的帖子之前我都不知道。)

var canvas, context, ball_pos;

var BALL_RADIUS = 15;

function start() {
    'use strict';
    canvas = document.getElementById('c');
    context = canvas.getContext('2d');
    ball_pos = [canvas.width / 2, canvas.height / 2];
}

function draw() {
    'use strict';

    // draw background
    context.fillStyle = "rgb(248,248,248)"; // off white
    context.fillRect(0, 0, canvas.width, canvas.height);

    // draw ball
    context.strokeStyle = 'black';
    context.lineWidth = 1;
    context.fillStyle = 'red';
    context.beginPath();
    context.arc(ball_pos[0], ball_pos[1], BALL_RADIUS, 0, Math.PI * 2, true);
    context.closePath();
    context.fill();
    context.stroke();
}

function animate() {
    'use strict';
    window.requestAnimationFrame(animate);
    draw();
}

function click(evt) {
  ball_pos[0] = evt.clientX - canvas.offsetLeft;
  ball_pos[1] = evt.clientY - canvas.offsetTop;
}

// register event handlers
window.onclick = click;

start();
animate();
<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <canvas id="c" width="600" height="400"></canvas>
</body>
</html>

0 个答案:

没有答案