欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

让canvas 支持鼠标事件

程序员文章站 2022-07-14 21:21:42
...
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;
}