码迷,mamicode.com
首页 > 其他好文 > 详细

canvas添加事件

时间:2019-04-09 00:13:43      阅读:447      评论:0      收藏:0      [点我收藏+]

标签:lse   function   win   set   事件   math   fse   画布   interval   

<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()
   }

}

 

canvas添加事件

标签:lse   function   win   set   事件   math   fse   画布   interval   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!