让canvas 支持鼠标事件

canvas里的图像不支持自定义事件,多少给编程带来点麻烦,好在有context.isPointInPath(x,y)方法,利用它可以判断给定的左边是否在当前路径中.当鼠标事件发生时,对现有的图形进行重绘,调用此方法进行判断,就可以知道点击的是哪个图形了.
多余的不说了,看看关键代码
$(function(){
g_shapes = []; //保存所有图形
var rect = $("#dia")[0].getBoundingClientRect();
var tPoint = {"x":rect.left,"y":rect.top}; //canvas位置
ctx = $("#dia")[0].getContext("2d");

var c1 = new shape("c1",100,300);
c1.click = function(e){
alert(this.name+" was clicked at "+e.x+","+e.y);
}

var c2 = new shape("c2",400,300,"#800040");
c2.click = function(e){
alert(this.name+" was clicked at "+e.x+","+e.y);
}

$("#dia").click(function(env){
var point = {"x":env.pageX-tPoint.x,"y":env.pageY-tPoint.y};
for(var i=0;i<g_shapes.length;i++){
g_shapes[i].reDraw(point);
}
}).mousemove(function(env){
var point = {"x":env.pageX-tPoint.x,"y":env.pageY-tPoint.y};
$("#pp").html(point.x+","+point.y);
});
});

function shape(name,x,y,color){
this.name = name;
this.click = null;
this.x = x;
this.y = y;
this.r = 40
this.color = color || "#000000";

ctx.beginPath();
ctx.moveTo(this.x, this.y - this.r);
ctx.arc(this.x, this.y, this.r, 2 * Math.PI, 0, true);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
g_shapes.push(this);
}

shape.prototype.reDraw = function(point){
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.x, this.y, this.r, 2 * Math.PI, 0, true);
if (ctx.isPointInPath(point.x,point.y)) {
$("#console").append("<li>"+this.name+" was clicked"+"</li>");
this.click.call(this,point);
}
ctx.closePath();
}

shape.prototype.click = function(fn){
this.click = fn;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值