Canvas How to - Draw shapes inside clipped area








Question

We would like to know how to draw shapes inside clipped area.

Answer


<!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).load(function(){<!--  w  w  w.  j  av  a2s . co  m-->
    var ctx = document.getElementById('canvas').getContext('2d');
    ctx.fillRect(0, 0, 150, 150);
    // create a clipping path
    ctx.beginPath();
    ctx.moveTo(20, 20);
    ctx.lineTo(20, 130);
    ctx.lineTo(130, 130);
    ctx.lineTo(130, 20);
    ctx.clip();
    // backgroud in clipped area
    ctx.fillStyle = "#11c";
    ctx.fillRect(0, 0, 150, 150);
    // draw shapes inside clipped area
    ctx.translate(75, 90);
    ctx.fillStyle = '#f00';
    ctx.fillRect(-15, -40, 40, 40);
    ctx.fillRect(0, 0, 10, 10);
    ctx.fillRect(-25, 10, 60, 60);
});//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width="150" height="150"></canvas>
</body>
</html>

The code above is rendered as follows: