HTML5 Canvas Tutorial: clipping regions

canvas clipping region

To define a clipping region using HTML5 canvas, we can draw the cut area and then use the clip () method of the canvas context

context.clip();

Example 1Canvas with circular clipping region. See image 1.

<!doctype html>
<html>
<head>
<script> 
    function drawClipingRegion() 
        {	
            var canvas=document.getElementById("figures");	
            var context=canvas.getContext("2d"); 	
            var centerX = canvas.width / 2;    	
            var centerY = canvas.height / 2;    	
            var radius = 75;     	
            var offset = 50;    	
            
            // Definieer de circelvormige clipping region.		
            // save () allows us to save the canvas context 
            // before we define the clipping region so we can 
            // return later to the base state   	
            context.save();    	
            context.beginPath();    	
            context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);    	
            context.clip();				
            
            // draw a blue square (top right) in the clipping region
            var topLeftCornerX = centerX;       
            var topLeftCornerY = centerY-75;       
            var width = 75;       
            var height = 75;        
            context.beginPath();       
            context.rect(topLeftCornerX,topLeftCornerY,width,height);       
            context.fillStyle="#00D2FF";// licht blauw      
            context.fill();          		
             
            // Draw a blue square (bottom left) in the clipping region	
            var topLeftCornerX = centerX-75;       
            var topLeftCornerY = centerY;       
            var width = 75;       
            var height = 75;        
            context.beginPath();       
            context.rect(topLeftCornerX,topLeftCornerY,width,height);      
            context.fillStyle="#00D2FF";// licht blauw       
            context.fill();   		
             
            // Draw a black circle around the clipping region	
            // restore() restores the canvas context to the 
            // original state before we defined the clipping region
            context.restore();   	
            context.beginPath();    	
            context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);    	
            context.lineWidth = 40;    	
            context.strokeColor = "black";    	
            context.stroke();	
		};        

    window.addEventListener("load", drawClipingRegion, true); 
</script>
</head>
<body>	
	<canvas id="figures" style="border: 1px solid;" width="350" height="250"></canvas>
</body>
</html>
Canvas met clipping region
Image 1. Canvas with circular clipping region

Check this example in your browser

Next tutorial

Leave a comment