gpt4 book ai didi

javascript - 通过单击事件识别 Canvas 上的对象

转载 作者:行者123 更新时间:2023-12-03 10:26:49 26 4
gpt4 key购买 nike

在这个简单的代码中,我使用了一个看起来根本不起作用的事件监听器。 Canvas 显示图像,并且给定的 hitpaint() 函数应该确定是否发生点击。我无法理解为什么 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;
}

最后,主循环将图片随机显示到 Canvas 中:

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);
}

最佳答案

这里有一些问题:

  • 正如 Grundy 在评论中指出的那样,hitpaint 从未被调用;现在它检查它是否存在并且总是返回 true
  • 鼠标坐标风险最终以小数值形式结束,这对于 getImageData 来说是不行的
  • 通常不需要缩放鼠标坐标。 Canvas 最好具有固定尺寸,无需额外的 CSS 尺寸
  • 为 x/y 添加边界检查,以确保它们位于 Canvas 位图内

我建议重写:

mycanv.addEventListener("click", function(e) {
var output = document.getElementByID("output");
ctx.fillStyle = 'blue';
//ctx.clearRect(0,0,100,20);

if (hitpaint(e)) { // here, call 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 x = ((mouse_event.clientX - bounding_box.left) *
(mycanv.width / bounding_box.width))|0; // |0 cuts off any fraction
var y = ((mouse_event.clientY - bounding_box.top) *
(mycanv.height / bounding_box.height))|0;

if (x >= 0 && x < mycanv.width && y >= 0 && y < mycanv.height) {
// as we only have one pixel, we can address alpha channel directly
return ctx.getImageData(x, y, 1, 1).data[3] !== 0;
}
else return false; // x/y out of range
}

关于javascript - 通过单击事件识别 Canvas 上的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29366664/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com