Canvas How to - Mask an image to the canvas








Question

We would like to know how to mask an image to the canvas.

Answer


<!--from ww  w  .j  a  va  2 s. co  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');
img.onload = function () {
    // Save the state, so we can undo the clipping
    ctx.save();
    // Create a shape, of some sort
    ctx.beginPath();
    ctx.moveTo(10, 10);
    ctx.lineTo(100, 30);
    ctx.lineTo(180, 10);
    ctx.lineTo(200, 60);
    ctx.arcTo(180, 70, 120, 0, 10);
    ctx.lineTo(200, 180);
    ctx.lineTo(100, 150);
    ctx.lineTo(70, 180);
    ctx.lineTo(20, 130);
    ctx.lineTo(50, 70);
    ctx.closePath();
    // Clip to the current path
    ctx.clip();
    ctx.drawImage(img, 0, 0);
    // Undo the clipping
    ctx.restore();
}
img.src = "http://www.java2s.com/style/download.png";
}//]]>  
</script>
</head>
<body>
  <canvas id="c" width="200" height="158"></canvas>
</body>
</html>

The code above is rendered as follows: