我目前在使用HTML5和JavaScript的<canvas>
标记中有两个圆圈。
现在,我尝试添加基于鼠标悬停和单击而更改的图像(完成)。
基本上,这是播放/暂停按钮的实现,当用户将鼠标悬停在按钮上时,按钮会进行额外的颜色更改。
我似乎无法弄清楚事件是如何在HTML5中的形状上工作的,因为它们不是对象……这是我目前的代码:
window.onload = function() {
var canvas = document.getElementsByTagName('canvas')[0];
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
//Outer circle
context.beginPath();
context.arc(centerX, centerY, 150, 0, Math.PI * 2, false);
context.fillStyle = "#000";
context.fill();
context.stroke();
//Inner cicle
context.beginPath();
context.arc(centerX, centerY, 75, 0, Math.PI * 2, false);
context.fillStyle = "#fff";
context.fill();
context.stroke();
//Play / Pause button
var imagePlay = new Image();
var imageHeight = 48/2;
imagePlay.onload = function() {
context.drawImage(imagePlay, centerX - imageHeight, centerY - imageHeight);
};
imagePlay.src = "images/play.gif";
}
1)如何处理用
<canvas>
创建的形状上的事件?2)用另一张图像替换
<canvas>
时,如何清理/移除图像?提前致谢 !
最佳答案
从技术上讲,无法在画布绘制的形状上注册鼠标事件。但是,如果使用类似Raphael(http://raphaeljs.com/)的库,它可以跟踪形状位置,从而确定接收鼠标事件的形状。这是一个例子:
var circle = r.circle(50, 50, 40);
circle.attr({fill: "red"});
circle.mouseover(function (event) {
this.attr({fill: "red"});
});
如您所见,这种方式非常简单。对于修改形状,该库也将派上用场。没有它,您将需要记住如何在每次更改时重新绘制所有内容