HTML5 Canvas moving alpha mask - Javascript Canvas

Javascript examples for Canvas:Mask

Description

HTML5 Canvas moving alpha mask

Demo Code

ResultView the demo in separate window

<!doctype html>
<html>
   <head> 
      <!-- reset css --> 
      <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> 
      <style>

canvas{border:1px solid red;}

      </style> 
      <script>
    $(function(){/* w  ww.  j a  v a2s  .co  m*/
        var canvas=document.getElementById("canvas");
        var ctx=canvas.getContext("2d");
        window.requestAnimFrame = (function(callback) {
          return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
          function(callback) {
            window.setTimeout(callback, 1000 / 60);
          };
        })();
        var radius=50;
        var x=100;
        var dx=10;
        var y=100;
        var dy=10;
        var delay=10;
        var img=new Image();
        img.onload=function(){
            var canvas1=document.getElementById("image");
            var ctxImg=canvas1.getContext("2d");
            ctxImg.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height);
            animate();
        }
        img.src="https://www.java2s.com/style/demo/Google-Chrome.png";
        function animate() {
          if(--delay<0){
                    // update
                    x+=dx;
                    if(x-radius<0 || x+radius>=canvas.width){dx=-dx;}
                    y+=dy;
                    if(y-radius<0 || y+radius>=canvas.height){dy=-dy;}
                    delay=10;

                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.save();
                    ctx.beginPath();
                    ctx.arc(x,y, radius, 0, 2 * Math.PI, false);
                    ctx.clip();
                    ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height);
                    ctx.restore();
          }

          requestAnimFrame(function() {
            animate();
          });
        }
    }); // end $(function(){});

      </script> 
   </head> 
   <body> 
      <p>Image clipped by moving circle</p> 
      <canvas id="canvas" width="300" height="200"></canvas> 
      <br>
      <p>Unclipped image</p> 
      <canvas id="image" width="300" height="200"></canvas>  
   </body>
</html>

Related Tutorials