画布元素:单击的图像
我想知道用户是否单击了画布中绘制的图像。我点击图像但没有任何反应。警报没有被调用。最后一个 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>
I want to know if the user clicked over an image drawed in a canvas. I click over the image but nothing happens. The alert isn't called. The last if condition never pass. Any idea?
<!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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有两个问题。
首先,你的事件代码坏了
screenX
返回的是鼠标相对于screen的位置,你需要使用clientX
或者在IE中pageX
请参阅 quirksmode 了解更多信息。其次,代码永远不会在 Chrome 中运行!它在第 15 行失败,并显示
Uncaught TypeError: DOM object constructor cannot be call as a function.
。创建图像时需要使用new
关键字,因为不能保证它否则,Image()
将返回一个新实例。Two problems here.
First, your event code is broken
screenX
returns the mouse position relative to the screen, you need to useclientX
or in IEpageX
see quirksmode for more information.Second, the code never runs in Chrome! It fails with
Uncaught TypeError: DOM object constructor cannot be called as a function.
at line 15. You need to use thenew
keyword when creating the image, since it's not guaranteed otherwise, that theImage()
will return a new instance.