[html5 教程]Html5 Canva中绘制的元素添加鼠标事件实例教程

更新时间:2019-12-26    来源:css3教程    手机版     字体:

【www.bbyears.com--css3教程】

使用jTopo给Html5 Canva中绘制的元素添加鼠标事件

使用Html5的时候,在Canvas上绘制的东西是不能相应鼠标事件的,但是使用jTopo添加事件非常简单,效果如下:


代码示例:

var node = new JTopo.Node("Hello");
node.setLocation(409, 269);
node.mousedown(function(event){
if(event.button == 2){
node.text = '按下右键';
}else if(event.button == 1){
node.text = '按下中键';
}else if(event.button == 0){
node.text = '按下左键';
}
});
node.mouseup(function(event){
if(event.button == 2){
node.text = '松开右键';
}else if(event.button == 1){
node.text = '松开中键';
}else if(event.button == 0){
node.text = '松开左键';
}
});
node.click(function(event){
console.log("单击");
});
node.dbclick(function(event){
console.log("双击");
});
node.mousedrag(function(event){
console.log("拖拽");
});
node.mouseover(function(event){
console.log("mouseover");
});
node.mousemove(function(event){
console.log("mousemove");
});
node.mouseout(function(event){
console.log("mouseout");
});



实例二


问:用HTML5的canvas画的一个图,如何添加鼠标事件(如:移入,点击),感谢各位的指点!


回答一:

面向对象就可以

一个是你找找对象化的canvas框架  比如canvasjs

一个是你自己写对象结构

简单说你canvas里面所有画的元素都是对象 比如那个 圆圈  比如那个线条

每个对象都要 实现 鼠标事件 mouseon 等等 每个对象要知道自己的坐标和大小(矩形大小)

但是怎么触发?  在canvas上绑定所有鼠标事件  然后  检查坐标看那个对象被触及了 然后调用该对象 相应的鼠标事件


回答二:

不是给图形添加鼠标事件,而是在鼠标事件中判断鼠标下是哪个图形。如






<script type="text/javascript">
    var list=[];
    var currentC;
    var _e={};
    var cricle = function(x,y,r){
        this.x=x;
        this.y=y;
        this.r=r;
        this.isCurrent=false;
        this.drawC=function(ctx,x,y){
            ctx.save();
            ctx.beginPath();
            ctx.moveTo(this.x,this.y-this.r);
            ctx.arc(this.x,this.y,this.r,2*Math.PI,0,true);
            if ((x && y && ctx.isPointInPath(x, y) && !currentC )||this.isCurrent) {
                    
                    ctx.fillStyle = '#ff0000';
                    currentC=this;
                    this.isCurrent=true;
            }else{
                ctx.fillStyle = '#999999';
            }
            ctx.fill();
        }
    
    }
    function draw(){
        var canvas = document.getElementById('tutorial');
        if (canvas.getContext){
            var ctx = canvas.getContext('2d');
            for(var i=0;i<10;i++){
                var c=new cricle(20*i,20*i,5*i);
                c.drawC(ctx);
                list.push(c);
            }
        }
    }
    
    function reDraw(e){
        e=e||event;
        var canvas = document.getElementById('tutorial');
        var x = e.clientX - canvas.offsetLeft;
        var y = e.clientY - canvas.offsetTop;
        canvas.width = canvas.width;
        if (canvas.getContext){
            var ctx = canvas.getContext('2d');
            for(var i=0;i
  canvas { border: 1px solid black; }



    


本文来源:http://www.bbyears.com/css/83813.html