Canvas How to - Clip an image








Question

We would like to know how to clip an image.

Answer


<!--  w ww.j  ava 2 s  .  c  om-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var objImg = new Image();
    objImg.onload = function(){ drawIt();}
    objImg.src = "http://www.java2s.com/style/download.png";
    function drawIt(){
      var canvas = document.getElementById("canvas-id");
      if(canvas.getContext){
        var ctx= canvas .getContext('2d');
        ctx.beginPath();
        ctx.rect(0, 0, 100, 100);
        ctx.clip();
        ctx.drawImage(objImg, 0, 0);
      }
    }
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas-id" width="100" height="100" ></canvas>
</body>
</html>

The code above is rendered as follows: