Canvas How to - Clip image on canvas








Question

We would like to know how to clip image on canvas.

Answer


<!DOCTYPE html>
<html>
<head>
<title>Image clipping versus clipping - jsFiddle demo by
  AbdiasSoftware</title>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--   w w w.j a  v a 2 s .com-->
var img = new Image();
img.onload = function() {

    var w = demo1.width,
        h = demo1.height,
        rect = [50, 200, 200, 150]
        ctx = demo1.getContext('2d');
    ctx.drawImage(this, 0, 0);
    ctx.fillStyle = 'rgba(0, 123, 0, 0.3)';
    ctx.fillRect(0, 0, w, h);
    ctx.drawImage(this, rect[0], rect[1], rect[2], rect[3],
                        rect[0], rect[1], rect[2], rect[3]);

    ctx = demo2.getContext('2d');
    ctx.drawImage(this, 0, 0);
    ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
    ctx.fillRect(0, 0, w, h);

    ctx.save();
    ctx.beginPath();
    ctx.rect(rect[0], rect[1], rect[2], rect[3]);
    ctx.clip();
    ctx.drawImage(this, 0, 0);
    ctx.restore();
}
img.src = 'http://www.java2s.com/style/download.png';
}//]]>  
</script>
</head>
<body>
  <canvas id="demo1" width=500 height=411></canvas>
  <canvas id="demo2" width=500 height=411></canvas>
  <canvas id="demo3" width=500 height=411></canvas>
</body>
</html>

The code above is rendered as follows: