0
在这个简单的代码中,我使用了一个看起来根本不起作用的eventListener。画布显示图像,并假定给定的函数确定是否发生点击。我不明白为什么eventListener的行为如此。任何见解都会有所帮助。通过点击事件在画布上标识对象
mycanv.addEventListener("click", function(e) {
var output = document.getElementByID("output");
ctx.fillStyle = 'blue';
//ctx.clearRect(0,0,100,20);
if (hitpaint) {
//ctx.fillText("hit",100,20);
output.innerHTML = "hit";
} else {
//ctx.fillText("miss",100,20);
output.innerHTML = "miss";
}
}, false);
的hitpaint()
函数被定义为:
function hitpaint(mouse_event) {
var bounding_box = mycanv.getBoundingClientRect();
var mousex = (mouse_event.clientX - bounding_box.left) *
(mycanv.width/bounding_box.width);
var mousey = (mouse_event.clientY - bounding_box.top) *
(mycanv.height/bounding_box.height);
var pixels = ctx.getImageData(mousex, mousey, 1, 1);
for (var i = 3; i < pixels.data.length; i += 4) {
// If we find a non-zero alpha we can just stop and return
// "true" - the click was on a part of the canvas that's
// got colour on it.
if (pixels.data[i] !== 0) return true;
}
// The function will only get here if none of the pixels matched in
return false;
}
最后,这显示在随机位置的图片到画布中主循环:
function start() {
// main game function, called on page load
setInterval(function() {
ctx.clearRect(cat_x, cat_y, 100, 100);
cat_x = Math.random() * mycanv.width - 20;
cat_y = Math.random() * mycanv.height - 20;
draw_katy(cat_x, cat_y);
}, 1000);
}
这里'如果(hitpaint)'你不叫'hitpaint'只是检查其是否存在,所以它总是_true_ – Grundy 2015-03-31 10:42:43
的行为像什么? – 2015-03-31 10:42:47
@SergiuParaschiv为什么它忽略了Listener。 – b10n1k 2015-03-31 10:51:00