canvas探照燈效果

來源:互聯網
上載者:User
  canvas中的clip()方法用於從原始畫布中剪下任意形狀和尺寸。一旦剪下了某個地區,則所有之後的繪圖都會被限制在被剪下的地區內(不能訪問畫布上的其他地區)

  也可以在使用clip()方法前通過使用save()方法對當前畫布地區進行儲存,並在以後的任意時間通過restore()方法對其進行恢複

  接下來使用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://www.php.cn/';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>
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.