canvas中的clip()方法用於從原始畫布中剪切任意形狀和尺寸。一旦剪切了某個區域,則全部以後的繪圖都會被限制在被剪切的區域內(不能訪問畫布上的其餘區域)html
也能夠在使用clip()方法前經過使用save()方法對當前畫布區域進行保存,並在之後的任意時間經過restore()方法對其進行恢復canvas
接下來使用clip()方法實現一個探照燈效果瀏覽器
<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); } } } 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(); } } initial(); clearInterval(oTimer); function fnInterval(){ //更新運動狀態 update(); //渲染 render(); } var oTimer = setInterval(fnInterval,50); </script>