是否有一个 html5 js 框架可以轻松地将事件(例如点击)添加到画布中的动画元素
或者您是否必须通过在画布上添加一个单击事件然后在单击位置正确时通过鼠标坐标进行计算?
下面是我写的一个脚本,但它运行得不是很好。有没有更简单的方法?谢谢
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.9.1.min.js"></script>
</head>
<body >
<canvas id="myCanvas" width="500" height="500" style="border:1px solid red; position: absolute; top:0; left:0;">
<p>Your browser doesn't support canvas.</p>
</canvas>
</body>
</html>
<script type ="text/javascript">
var context;
var myRect = [];
function Shape(x, y, w, h, fill) {
this.speedX = 1;
this.speedY = 1;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.fill = fill;
}
// get canvas element.
var elem = document.getElementById('myCanvas');
// check if context exist
if (elem.getContext) {
context = elem.getContext('2d');
myRect.push(new Shape(10, 0, 25, 25, "#333"))
myRect.push(new Shape(0, 40, 39, 25, "#333"))
myRect.push(new Shape(0, 80, 100, 25, "#333"))
}
function loop() {
//console.log('tick');
context.clearRect(0, 0, elem.width, elem.height);
for (i in myRect) {
//console.log(x);
context.fillRect(myRect[i].x, myRect[i].y, myRect[i].w, myRect[i].h)
myRect[i].x += myRect[i].speedX;
//if (myRect[i].x >= elem.width - myRect[i]) {
//}
console.log(myRect[1].x + ' ' + myRect[1].y);
//context.fillStyle = i.fill;
}
//context.clearRect(0, 0, elem.width, elem.height);
//context = elem.getContext('2d');
}
setInterval(loop, 25);
$('#myCanvas').click(function (evt) {
var mouseX = evt.pageX;
var mouseY = evt.pageY;
//console.log('mouseX ' + mouseX + ' mouseY ' + mouseY);
if (myRect[1].x < (mouseX + myRect[1].w) && myRect[1].x > mouseX && myRect[1].y < (mouseY + myRect[1].h) && myRect[1].y > mouseY) {
alert('test');
}
});
</script>