HTML5 Canvas Tutorial: transformations – basics

Translations on the canvas: basics

On a HTML5 Canvas there are multiple ways to move a figure, rotate, scale and more. In other words, there are multiple ways a figure can be transformed.

For example, we can move a diagonal line in two different ways on : by using the moveTo() method or by using the translate() method, see Example 1 and Example 2 below. In the accompanying images 1 and 2, the relating coordinates of the canvas context are drawn as well . Note the difference between the position of the origin (0,0) in both images.

Example 1: Moving a diagonal by means of the moveTo() method of the canvas context. See image 1.


<html>
<head>
<title>Verplaatsing van een diagonaal mbv de moveTo() methode</title>
<script> 
    function tekenDiagonaal() { 
      // Get the canvas element and its drawing context 
      var canvas = document.getElementById("diagonal"); 
      var context = canvas.getContext("2d"); 
      
      // Create a path in absolute coordinates 
      context.beginPath(); 
      context.moveTo(70, 140);
	  context.lineWidth=7;     
      context.strokeStyle="#f16529"; 
      context.lineTo(210, 70); 
      
      // Stroke the line onto the canvas 
      context.stroke(); 
      };
    
       window.addEventListener("load", tekenDiagonaal, true); 
</script>
</head>
<body>	
	<canvas id="diagonal" style="border: 1px solid;" width="400" height="210"></canvas>
</body>
</html>

Canvas Transformaties: de basis.
Image 1. Displacement of a diagonal relative to the origin (0,0) with the help of the moveTo() method.

Check this example in your browser

Example 2: Moving a diagonal by means of the translate () method of the canvas context. See image 2.

<!doctype html>
<html>
<head>
<title>Verplaatsing van een diagonaal mbv de translate() methode </title>
<script> 
    function drawDiagonal2() {  
         var canvas = document.getElementById("diagonal");  
         var context = canvas.getContext("2d");  
          
         // Save a copy of the current drawing state  
         context.save();  
          
         // Move the drawing context to the right, and down  
         context.translate(70, 140);  
          
         // Draw the same line as before, but using the origin as a start  
         context.beginPath();  
         context.moveTo(0, 0); 
         context.lineWidth=7;     
      	 context.strokeStyle="#f16529";  
         context.lineTo(140, -70);  
         context.stroke();  
          
         // Restore the old drawing state  
         context.restore();  
         } 
    
    window.addEventListener("load", drawDiagonal2, true);
</script>
</head>
<body>	
	<canvas id="diagonal" style="border: 1px solid;" width="400" height="210"></canvas>
</body>
</html>
Canvas Transformaties: de basis.
Image 2. Displacement diagonally relative to the origin (0,0) with the help of the translate () method.

Check this example in your browser

Next tutorial

Leave a comment