画布元素:单击图像

时间:2010-12-02 18:41:58

标签: javascript css canvas position

我想知道用户是否点击了画布上绘制的图像。我点击图片但没有任何反应。警报未被调用。最后的if条件永远不会通过。有什么想法吗?

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <div id="wrapper">
            <canvas id="game" height="500" width="700">
            </canvas>
        </div>
        <script>
        (function() {
            var canvas = document.getElementById('game'),
                context = canvas.getContext('2d'),
                fps = 1,
                character = Image(),
                positions = [[125, 55], [480, 55], [125, 185], [480, 182], [125, 315], [480, 315]],
                random, x, y, xc, yc = null;

            canvas.addEventListener('click', function(event) {
                xc = event.screenX - canvas.offsetLeft;
                yc = event.screenY - canvas.offsetTop;

                if((xc >= x) && (xc <= (x + character.width)) && (yc >= y) && (yc <= (y + character.height))) {
                    alert('X = ' + x + 'Y = ' + y);
                }
            }, true);

            character.src = 'character.png';

            setInterval(function() {
                random = (Math.floor(Math.random() * 6));

                random = positions[random];
                x = random[0];
                y = random[1];

                context.clearRect(0, 0, canvas.width, canvas.height);
                context.drawImage(character, x, y);
            }, 1000 / fps);
        }());
        </script>
    </body>
</html>

1 个答案:

答案 0 :(得分:2)

这里有两个问题。

首先,您的事件代码已损坏screenX返回相对于屏幕的鼠标位置,您需要使用clientX或在IE pageX中查看{ {3}}了解更多信息。

canvas.addEventListener('click', function(event) {
    event = event || window.event; // IE does not pass the event param!

    // you should use var infront of these local variables
    // otherwise you leak them into the global namespace
    // and you can even overwrite things there if you don't watch out
    var xc = (event.clientX ? event.clientX : pageX) - canvas.offsetLeft;
    var yc = (event.clientY ? event.clientY : pageY) - canvas.offsetTop;

其次,代码永远不会在Chrome中运行!它在第15行失败并显示Uncaught TypeError: DOM object constructor cannot be called as a function.。您需要在创建图片时使用new关键字,否则无法保证Image()将返回新实例。

...
context = canvas.getContext('2d'),
fps = 1,
character = new Image(),
...