Animated image mask following mouse - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

Animated image mask following mouse

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
      <script type="text/javascript">
    $(window).load(function(){/*from   www .ja v  a 2s  .  c o m*/
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
can.addEventListener('mousemove', function(e) {
    var mouse = getMouse(e, can);
    redraw(mouse);
}, false);
function redraw(mouse) {
    console.log('a');
    can.width = can.width;
    ctx.drawImage(img, 0, 0);
    ctx.beginPath();
    ctx.rect(0,0,500,500);
    ctx.arc(mouse.x, mouse.y, 70, 0, Math.PI*2, true)
    ctx.clip();
    ctx.fillRect(0,0,500,500);
}
var img = new Image();
img.onload = function() {
    redraw({x: -500, y: -500})
}
        img.src = 'http://placekitten.com/500/500';
function getMouse(e, canvas) {
    var element = canvas,
        offsetX = 0,
        offsetY = 0,
        mx, my;
    // Compute the total offset. It's possible to cache this if you want
    if (element.offsetParent !== undefined) {
        do {
            offsetX += element.offsetLeft;
            offsetY += element.offsetTop;
        } while ((element = element.offsetParent));
    }
    mx = e.pageX - offsetX;
    my = e.pageY - offsetY;
    // We return a simple javascript object with x and y defined
    return {
        x: mx,
        y: my
    };
}
    });

      </script> 
   </head> 
   <body> 
      <canvas id="canvas1" width="500" height="500"></canvas>  
   </body>
</html>

Related Tutorials