HTML5 Game - The Canvas clipping region

Description

The Canvas clipping region

Demo

ResultView the demo in separate window

<!DOCTYPE html>  
<html> 
<head> 
<style> 
#canvas { //w  ww  .ja  v a2 s .c o m
  border:1px solid #03F; 
  background:#CFC; 
} 
</style> 
</head> 
<body> 
<canvas id="canvas" width="640" height="480"></canvas> 
<script> 
  let context = document.getElementById('canvas').getContext('2d'); 
    
      //draw a big box on the screen 
      context.fillStyle = "black"; 
      context.fillRect(10, 10, 200, 200); 
      context.save(); 
      context.beginPath();      //clip the canvas to a 50?50 square starting at 0,0 
      context.rect(0, 0, 50, 50); 
      context.clip(); 

      //red circle 
      context.beginPath(); 
      context.strokeStyle = "red"; 
      context.lineWidth = 5; 
      context.arc(100, 100, 100, (Math.PI/180)*0, (Math.PI/180)*360, false); 
      //full circle 
      context.stroke(); 
      context.closePath(); 

      context.restore(); 

      //reclip to the entire canvas 
      context.beginPath(); 
      context.rect(0, 0, 500, 500); 
      context.clip(); 

      //draw a blue line that is not clipped 
      context.beginPath(); 
      context.strokeStyle = "blue"; 
      context.lineWidth = 5; 
      context.arc(100, 100, 50, (Math.PI/180)*0, (Math.PI/180)*360, false); 
      //full circle 
      context.stroke(); 
      context.closePath(); 
</script> 



</body> 
</html>

Related Topic