当前位置: 移动技术网 > IT编程>网页制作>Html5 > canvas探照灯效果的示例代码

canvas探照灯效果的示例代码

2019年07月25日  | 移动技术网IT编程  | 我要评论

canvas中的clip()方法用于从原始画布中剪切任意形状和尺寸。一旦剪切了某个区域,则所有之后的绘图都会被限制在被剪切的区域内(不能访问画布上的其他区域)

也可以在使用clip()方法前通过使用save()方法对当前画布区域进行保存,并在以后的任意时间通过restore()方法对其进行恢复

接下来使用clip()方法实现一个探照灯效果

</iframe>
<button id="btn">变换</button>
<button id="con">暂停</button>
<canvas id="canvas" width="400" height="290" style="border:1px solid black">当前浏览器不支持canvas,请更换浏览器后再试</canvas>
<script> btn.onclick = function(){history.go();}
con.onclick = function(){ if(this.innerhtml == '暂停'){ this.innerhtml = '恢复';
        clearinterval(otimer);
    }else{ this.innerhtml = '暂停'; 
        otimer = setinterval(fninterval,50);
    }
} var canvas = document.getelementbyid('canvas'); //存储画布宽高
var h=290,w=400; //存储探照灯
var ball = {}; //存储照片
var img; //存储照片地址
var url = 'http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/chunfen.jpg'; function initial(){ if(canvas.getcontext){ var cxt = canvas.getcontext('2d'); var tempr = math.floor(math.random()*30+20); var tempx = math.floor(math.random()*(w-tempr) + tempr); var tempy = math.floor(math.random()*(h-tempr) + tempr)        
        ball = {
            x:tempx,
            y:tempy,
            r:tempr,
            stepx:math.floor(math.random() * 21 -10),
            stepy:math.floor(math.random() * 21 -10)
        };
        img = document.createelement('img');
        img.src=url;
        img.onload = function(){
            cxt.drawimage(img,0,0);
      }//欢迎加入全栈开发交流圈一起学习交流:582735936
    ]//面向1-3年前端人员
  }   //帮助突破技术瓶颈,提升思维能力
        }   
    }    
} function update(){
    ball.x += ball.stepx;
    ball.y += ball.stepy; 
    bumptest(ball);
} function bumptest(ele){ //左侧
    if(ele.x <= ele.r){
        ele.x = ele.r;
        ele.stepx = -ele.stepx;
    } //右侧
    if(ele.x >= w - ele.r){
        ele.x = w - ele.r;
        ele.stepx = -ele.stepx;
    } //上侧
    if(ele.y <= ele.r){
        ele.y = ele.r;
        ele.stepy = -ele.stepy;
    } //下侧
    if(ele.y >= h - ele.r){
        ele.y = h - ele.r;
        ele.stepy = -ele.stepy;
    }
} function render(){ //重置画布高度,达到清空画布的效果
 canvas.height = h; if(canvas.getcontext){ var cxt = canvas.getcontext('2d');
        cxt.save(); //将画布背景涂黑
 cxt.beginpath();
        cxt.fillstyle = '#000';
        cxt.fillrect(0,0,w,h); //渲染探照灯
 cxt.beginpath();
        cxt.arc(ball.x,ball.y,ball.r,0,2*math.pi);
        cxt.fillstyle = '#000';
        cxt.fill(); 
        cxt.clip(); //由于使用了clip(),画布背景图片会出现在clip()区域内
 cxt.drawimage(img,0,0);
        cxt.restore();
      }//欢迎加入全栈开发交流圈一起学习交流:582735936
    ]//面向1-3年前端人员
  }   //帮助突破技术瓶颈,提升思维能力
    }

}
initial();
clearinterval(otimer); function fninterval(){ //更新运动状态
 update(); //渲染
 render();    
} var otimer = setinterval(fninterval,50); 
</script> 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网