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