canvas添加事件

<canvas id="c1" width="800" height="600"></canvas>

1.画布内的元素移动

window.onload=function () {
    //图形动起来

    let oC = document.getElementById('c1');
    let gd = oC.getContext('2d');
    let L = 50;
    setInterval(()=>{
        gd.clearRect(0,0,oC.width,oC.height);//清除整个画布
        L++;
        gd.strokeRect(L,50,100,70)
    },10);

}

2.画布内的矩形元素添加事件

window.onload=function () {
//点击事件

let oC = document.getElementById('c1');
let gd = oC.getContext('2d');
let l = 50,t = 50,w = 100, h = 70;
gd.strokeRect(l,t,w,h);
oC.onclick = function (e) {
gd.clearRect(0,0,oC.width,oC.height);
if(e.offsetX>=l&&e.offsetX<=l+w&&e.offsetY>=t&&e.offsetY<=t+h){
gd.strokeStyle = 'red';
gd.strokeRect(l,t,w,h);
}else{
gd.strokeStyle = 'blue';
gd.strokeRect(l,t,w,h);
}
}

}

3.画布圆心区域添加事件

window.onload=function () {
    let oC = document.getElementById('c1');
    let gd = oC.getContext('2d');
   let cx=400,cy=300,r=200;
    gd.arc(cx,cy,r,0,2*Math.PI,true);
    gd.fillStyle='yellow';
    gd.fill();
   oC.onmousemove = function (e) {
       let a = e.offsetX-cx;
       let b = e.offsetY-cy;
       let dis = Math.sqrt(a*a+b*b)
       gd.beginPath();
       gd.arc(cx,cy,r,0,2*Math.PI,true);
       if(dis<=r){
           gd.fillStyle='blue'
       }else{
           gd.fillStyle='red'
       }
       gd.fill()
   }

}
原文地址:https://www.cnblogs.com/caoruichun/p/10674428.html