在画布上获取鼠标点击事件

5
我一直在尝试让我的简单JavaScript脚本将弹跳球移动到鼠标点击事件发生的位置。我在这里放置了脚本。它可以与任何具有id为game的大小不同的画布进行交互。球会弹跳,但它忽略了鼠标点击事件。你知道哪里出了问题吗?谢谢。
var canvas;
var x, y;
var dx=4;
var dy=4;
var d = 20;
var width, height;

function init() {
    canvasE = document.getElementById('game');
    canvas= canvasE.getContext('2d');
    width = canvasE.width;
    height = canvasE.height;
    x = d+dx+1;
    y = d+dy+1;
    canvasE.addEventListener("click", onClick, false);

    clear();

    canvas.beginPath();
    canvas.fillStyle="#0000ff";
    // Draws a circle of radius 20 at the coordinates 100,100 on the canvas
    canvas.arc(x-1,y-1,d,0,Math.PI*2,true);
    canvas.closePath();
    canvas.fill();
    setInterval(loop, 15);
}

function loop() {
    clear();

    canvas.beginPath();
    canvas.fillStyle="#0000ff";
    // Draws a circle of radius 20 at the coordinates 100,100 on the canvas
    canvas.arc(x,y,d,0,Math.PI*2,true);
    canvas.closePath();
    canvas.fill();
    // Boundary Logic
    if( x<(d-dx)+1 || x>width-(d+dx)-1) dx=-dx;
    if( y<(d-dx)+1 || y>height-(d+dy)-1) dy=-dy;
    x+=dx;
    y+=dy;
}
function clear() {
    canvas.fillStyle="#ffffff";
    canvas.fillRect(0,0,width,height);
    canvas.fillStyle="#888888";
    canvas.strokeRect(0,0,width,height);
}

function onClick(e) {
    var clickX;
    var clickY;
    if (e.pageX || e.pageY) { 
        clickX = e.pageX;
        clickY = e.pageY;
    }
    else { 
        clickX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 
        clickY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
    } 
    clickX -= gCanvasElement.offsetLeft;
    clickY -= gCanvasElement.offsetTop;
    x = clickX;
    y = clickY;
}
1个回答

7
这里有一些更合适的点击代码(虽然不能百分之百地防止错误),供您参考: http://jsfiddle.net/4Lanc/ 另外需要注意的是,如果您与其他Canvas程序员共同工作时,将“canvasE和canvas”而不是“canvas和context / ctx”用于命名约定可能会引起严重的混乱。我强烈建议改为使用“canvas和context / ctx”。

太棒了。非常感谢!你改了什么使它工作了? - user263078
看看 onClick 函数的差异。我不知道 gCanvasElement 是什么,所以我把它移除了。 - Simon Sarris
这是一个更新的版本,它使用requestAnimationFrame()而不是setTimeout()。http://jsfiddle.net/sperske/4Lanc/367/ - Jason Sperske

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接