Canvas How to - Overlap rectangles








Question

We would like to know how to overlap rectangles.

Answer


<!--from   ww w. j a v a2  s  .c  om-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
  var overlap_canvas = document.getElementById("overlap");
  var overlap_context = overlap_canvas.getContext("2d");
  var x = 200;
  var y = x;
  var rectQTY = 4 // Number of rectangles
    overlap_context.translate(x,y);
    for (j=0;j<rectQTY;j++){
         overlap_context.beginPath();
         overlap_context.rect(-90, -100, 180, 80);
         overlap_context.fillStyle = 'yellow';
         overlap_context.fill();
         overlap_context.lineWidth = 7;
         overlap_context.strokeStyle = 'blue';
         overlap_context.stroke();
        overlap_context.rotate((Math.PI/180)*360/rectQTY);
    }
}//]]>  
</script>
</head>
<body>
  <canvas id="overlap" width="400" height="400"></canvas>
</body>
</html>

The code above is rendered as follows: