Canvas How to - Create Fog image mask








Question

We would like to know how to create Fog image mask.

Answer


<!--from ww  w.java 2 s . c om-->


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).on('load', function () {
  var ctx = $('#canvas')[0].getContext('2d'),
    mouse = {x: -100, y: -100};
  ctx.fillStyle = 'black';
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  $('#canvas').on('mousemove.fog', function (evt) {
    mouse.x = evt.offsetX;
    mouse.y = evt.offsetY;
  });
  (function animloop(now) {
    var frame = webkitRequestAnimationFrame(animloop),
      x = mouse.x,
      y = mouse.y,
      r = 10,
      grad = ctx.createRadialGradient(x, y, 0, x, y, r);
    grad.addColorStop(0, "rgba(0, 0, 0, 255)");
    grad.addColorStop(1, "rgba(0, 0, 0, 0)");
    ctx.globalCompositeOperation = 'destination-out';
    ctx.fillStyle = grad;
    ctx.arc(x, y, r, 0, 2 * Math.PI, true);
    ctx.fill();
  }(Date.now()));
});
//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width="128" height="128"
    style="background: black url(http://www.java2s.com/style/download.png) center center; background-size: cover">
</canvas>
</body>
</html>

The code above is rendered as follows: