将事件处理程序附加到画布元素
在画布元素上绘图时,渲染的形状缺乏超出其像素的固有表示。这意味着单击事件不能直接附加到各个形状。
解决方案:
将单击处理程序添加到画布元素:
canvas.addEventListener('click', function() { /* Event handler code */ }, false);
要确定画布中的哪个元素被单击:
var canvas = document.getElementById('myCanvas'); // Get canvas offset and context var canvasLeft = canvas.offsetLeft + canvas.clientLeft; var canvasTop = canvas.offsetTop + canvas.clientTop; var context = canvas.getContext('2d'); // Array to store element data var elements = []; // Add 'click' event listener to canvas canvas.addEventListener('click', function(event) { // Calculate click coordinates relative to canvas var x = event.pageX - canvasLeft; var y = event.pageY - canvasTop; // Check for collision detection against elements elements.forEach(function(element) { if (y > element.top && y < element.top + element.height && x > element.left && x < element.left + element.width) { alert('Clicked an element'); // TODO: Additional actions (e.g., remove element, update canvas) } }); }, false);
尝试失败:
以上是如何将事件处理程序附加到画布元素并检测形状上的点击?的详细内容。更多信息请关注PHP中文网其他相关文章!