通过单击事件识别画布上的对象
identify an object on canvas by a click event
在这个简单的代码中,我使用了一个看起来根本不起作用的eventListener。画布显示一个图像,并且假定给定的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;
}
最后,在画布中随机显示图片的主循环:
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不符
- 通常不需要缩放鼠标坐标。画布最好具有固定的大小,而不需要额外的CSS大小
- 为x/y添加边界检查,以确保它们位于画布位图内
我建议重写:
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
}
相关文章:
- 识别没有ID或特定属性的对象
- 识别由不同数量的项组成的json对象
- 通过单击事件识别画布上的对象
- Google Closure Advanced |无法识别对象属性|动态属性
- 拖放无法识别动画CC中拖动对象的子对象
- 无法识别的数据结构-转换为对象
- 是否可以在函数构造函数中识别哪个对象调用它,并在错误的对象调用时中止创建
- 通过放置在对象中来识别对象特性
- 为什么无法识别mssql对象
- JavaScript 如何重新识别事件对象变量
- 无法识别余烬对象
- jQuery 插件 datetimepicker 未被 Date() 对象包装器识别为日期的问题
- 如何识别所选对象的类型
- 语法错误,无法识别的表达式:[对象 HTMLDivElement]输入:复选框[名称=]:选中
- jQuery-通过对象在兄弟对象中的位置(索引)来识别对象
- Javascript对象未被识别为addEventListener的DOM对象
- 如何使用角度模块在视图中识别模型对象
- JavaScript对象无法识别属性
- 无法识别字段-未标记为可忽略错误-JSON-Java对象
- 试图让一个对象识别它的父对象,而不把父对象传递给子对象的实例