我在 Canvas 上使用 CSS 设置了背景图片;这是一张 map 。
然后我在 map 顶部的各个点上“绘制”红色图钉图像。每个图钉都被绘制为一个新的 Image 对象,名称不同但源图像相同。
我希望这些图像引脚可以交互(onMouseOver/onClick/等),但是当我尝试执行以下代码时我没有看到任何事件触发:
<body>
<canvas id="backgroundMapCanvas" width="1177" height="669"></canvas>
</body>
<style type="text/css" media="screen">
canvas {
background:url(images/mapBackground2.jpg)
}
</style>
<script type="text/javascript">
var canvas = document.getElementById("backgroundMapCanvas");
var context = canvas.getContext("2d");
var pinMelbourne = new Image();
pinMelbourne.src = "images/redPin3.png";
pinMelbourne.onload = function() {
context.drawImage(pinMelbourne, 987, 538);
};
pinMelbourne.onmouseover = function() {
alert("test alert box");
};
</script>
谢谢,
维拉特
最佳答案
您必须将事件添加到 Canvas 对象,而不是图像。图像绘制在 Canvas 上,但实际图像对象从未添加到页面中。要检测鼠标是否移到 Canvas 上的图像上,您需要检查边界框。
canvas.addEventListener('movemove', function(e) {
var x = e.layerX; // x and y coordinated relative to top-left corner of canvas
var y = e.layerY;
if (x >= 987 && x < 987 + pinMelbourne.width && y >= 538 && y < 538 + pinMelbourne.height) {
alert('Mouse over image');
}
})
关于javascript - 我可以使 javascript Image 对象具有交互性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30017143/