我的 javascript 代码没有运行,但绘制画布的 html 是.....我试图在画布 html 元素上添加一个事件侦听器。每次我点击它应该给我一个警报的元素。我在 Firefox 和 google chrome 上试过这个。
<script language = "javascript" type = "text/javascript">
alert("yo");
canvas.addEventListener('click', function() {}, false);
var elem = document.getElementById("checkersq"),
elemLeft = elem.offsetLeft,
elemTop = elem.offsetTop,
context = elem.getContext('2d'),
elements = [];
elem.addEventListener('click', function(event){
var x = event.pageX - elemLeft,
y = event.pageY - elemTop;
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');
}
}
});
}, false);
elements.push({
colour: '#05EFFF',
width: 150,
height: 200,
top: 20,
left: 15
});
elements.forEach(function(element) {
context.fillStyle = element.colour;
context.fillRect(element.left, element.top, element.width, element.height);
});