浏览 4386 次
锁定老帖子 主题:让canvas 支持鼠标事件
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2011-07-14
最后修改:2011-07-14
多余的不说了,看看关键代码 $(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; } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |