我不认为画布为其形状提供内部鼠标功能。你有两个选择
你可以做格兰特斯金纳用easeljs做的事情。您可以在临时画布上绘制一个形状,然后使用context.getImageData(left, top, width, height) 测试鼠标下的像素是否透明。好处是它可以通用而不需要知道形状的边界框。缺点是速度极慢。
像我一样,使用复杂的算法来确定一个点是在形状的内部还是外部。我会尝试为您设置一个 jsfiddle 示例。
这是一个 jsfiddle 示例 http://jsfiddle.net/pukster/HNA2z/1/ 它展示了如何使用纯 JavaScript 来捕获鼠标事件,并为矩形、圆形和复杂多边形做翻转效果。为矩形设置k=0,为圆形设置k=1,为多边形设置k=2(警告,代码非常混乱)。
盒子:
function Box(x,y,w,h){
this.x=x;
this.y=y;
this.w=w;
this.h=h;
this.color=cOut;
this.inside = false;
this.draw=function(){
ctx.fillStyle=this.color;
ctx.fillRect(this.x,this.y,this.w,this.h);
}
this.onMouseOver=function(){
this.color=cOver;
this.draw();
}
this.onMouseOut=function(){
this.color=cOut;
this.draw();
}
this.isInside = function(x,y){
return (this.x<=x) && (x<=this.x+this.w) && (this.y<=y) && (y<=this.y+this.h);
}
}
圈子:
function Circle(x,y,r){
this.x=x;
this.y=y;
this.r=r;
this.color=cOut;
this.inside = false;
this.draw=function(){
ctx.fillStyle=this.color;
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
this.onMouseOver=function(){
this.color=cOver;
this.draw();
}
this.onMouseOut=function(){
this.color=cOut;
this.draw();
}
this.isInside = function(x,y){
return Math.sqrt((this.x-x)*(this.x-x)+(this.y-y)*(this.y-y))<this.r;
}
}
多边形:
function Polygon(points){
this.points = points;
this.color=cOut;
this.inside = false;
this.draw=function(){
ctx.fillStyle=this.color;
ctx.beginPath();
var x,y;
x = this.points[0][0];
y = this.points[0][1];
ctx.moveTo(x, y);
for (var i = 1; i < this.points.length; i++){
x = this.points[i][0];
y = this.points[i][1];
ctx.lineTo(x, y);
}
ctx.closePath();
ctx.fill();
}
this.onMouseOver=function(){
this.color=cOver;
this.draw();
}
this.onMouseOut=function(){
this.color=cOut;
this.draw();
}
this.isInside = function(x,y){
for (var c = false, i = - 1, l = this.points.length, j = l - 1; ++i < l; j = i)((this.points[i][1] <= y && y < this.points[j][1]) || (this.points[j][1] <= y && y < this.points[i][1])) && (x < (this.points[j][0] - this.points[i][0]) * (y - this.points[i][1]) / (this.points[j][1] - this.points[i][1]) + this.points[i][0]) && (c = ! c);
return c;
}
}
鼠标捕获有点技术性,但这是我检查过渡的方法:
过渡:
function onMouseMove(e){
var x = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
var y = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
if (shape.isInside(x,y) && ! shape.inside){
shape.inside = true;
shape.onMouseOver();
}
else if (!shape.isInside(x, y) && shape.inside){
shape.onMouseOut();
shape.inside = false;
}
}