溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

canvas實現(xiàn)探照燈效果的方法

發(fā)布時間:2021-05-12 13:47:01 來源:億速云 閱讀:174 作者:小新 欄目:web開發(fā)

這篇文章將為大家詳細(xì)講解有關(guān)canvas實現(xiàn)探照燈效果的方法,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

canvas中的clip()方法用于從原始畫布中剪切任意形狀和尺寸。一旦剪切了某個區(qū)域,則所有之后的繪圖都會被限制在被剪切的區(qū)域內(nèi)(不能訪問畫布上的其他區(qū)域)

也可以在使用clip()方法前通過使用save()方法對當(dāng)前畫布區(qū)域進行保存,并在以后的任意時間通過restore()方法對其進行恢復(fù)

接下來使用clip()方法實現(xiàn)一個探照燈效果

<button id="btn">變換</button>
<button id="con">暫停</button>
<canvas id="canvas" width="400" height="290" >當(dāng)前瀏覽器不支持canvas,請更換瀏覽器后再試</canvas>
<script>
btn.onclick = function(){history.go();}
con.onclick = function(){
 if(this.innerHTML == '暫停'){
  this.innerHTML = '恢復(fù)';
  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 = 'https://cache.yisu.com/upload/information/20200622/114/77359.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);
  } 
 } 
}
function update(){
 ball.x += ball.stepX;
 ball.y += ball.stepY; 
 bumpTest(ball);
}
function bumpTest(ele){
 //左側(cè)
 if(ele.x <= ele.r){
  ele.x = ele.r;
  ele.stepX = -ele.stepX;
 }
 //右側(cè)
 if(ele.x >= W - ele.r){
  ele.x = W - ele.r;
  ele.stepX = -ele.stepX;
 }
 //上側(cè)
 if(ele.y <= ele.r){
  ele.y = ele.r;
  ele.stepY = -ele.stepY;
 }
 //下側(cè)
 if(ele.y >= H - ele.r){
  ele.y = H - ele.r;
  ele.stepY = -ele.stepY;
 }
}
function render(){
 //重置畫布高度,達(dá)到清空畫布的效果
 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(),畫布背景圖片會出現(xiàn)在clip()區(qū)域內(nèi)
  cxt.drawImage(IMG,0,0);
  cxt.restore();
 }
}
initial();
clearInterval(oTimer);
function fnInterval(){
 //更新運動狀態(tài)
 update();
 //渲染
 render(); 
}
var oTimer = setInterval(fnInterval,50);
</script>

關(guān)于“canvas實現(xiàn)探照燈效果的方法”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI