HTML5 Game - Scale and Translate Transformations

Description

Scale and Translate Transformations

Demo

ResultView the demo in separate window

<!DOCTYPE html> 
<html> 
    <head> 
        <title>Canvas Demo</title> 
        <style> 
canvas { /*from  w  w w.  j  av a  2s.c  om*/
  border: 1px solid #000; 
} 
        </style> 
    </head> 
    <body> 
      <canvas id="myCanvas" width="200" height="200">Did You Know: Every time 
        you use a browser that doesn't support HTML5
      </canvas> 
      <script> 
// Get the context we will be using for drawing. 
let myCanvas = document.getElementById('myCanvas'); 
let myContext = myCanvas.getContext('2d'); 
  
/** 
 * Draws a 100x100 square at (0, 0) in the specified color. Indicates the origin 
 * corner with a small black square. 
 * @param {string} color A valid CSS color string. 
 */ 
function drawSquare(color) { 
  myContext.fillStyle = color; 
  myContext.beginPath(); 
  myContext.rect(0, 0, 100, 100); 
  myContext.fill(); 
  myContext.fillStyle = '#000'; 
  myContext.beginPath(); 
  myContext.rect(0, 0, 5, 5); 
  myContext.fill(); 
} 
  
// Draw a square, fill it with red. 
drawSquare('rgba(255, 0, 0, 0.5)'); 
  
// Translate the canvas. 
myContext.translate(20, 40); 
  
// Scale the canvas. 
myContext.scale(1, 1.5); 
  
// Draw the same square again, fill it with blue. 
drawSquare('rgba(0, 0, 255, 0.5)'); 
  
// Translate the canvas again. 
myContext.translate(50, -20); 
  
// Scale the canvas again. 
myContext.scale(1.5, 1); 
  
// Draw the same square again, fill it with green. 
drawSquare('rgba(0, 255, 0, 0.5)'); 
      </script> 
    </body> 
</html>

Related Topic