HTML5 Game - Translating Canvas Positions

Description

Translating Canvas Positions

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
<head>
<script>
//Draws rectangles on a canvas.
window.onload = function()//from   w w w  .  j ava2 s  .c om
{
   canvas  = document.getElementById("canvasArea");
   context = canvas.getContext("2d");

   //SIZE of square.
   let size = 30;

   //         translateH  translateV  color
   //         ----------  ----------  --------
   drawSquare(         0,         0,  "gray"  );
   drawSquare(      size,      size,  "red"   );
   drawSquare(      size,     -size,  "blue"  );
   drawSquare(      size,         0,  "pink"  );
   drawSquare(      size,     -size,  "purple");
   drawSquare(    2*size,      size,  "green" );

   function drawSquare(translateH, translateV, color)
   {
      context.fillStyle = color;

      context.translate(translateH, translateV);

      context.fillRect(0, 0, size, size);
   }
}
</script>
</head>
<body>

<div    style = "width:300px;   height:125px;
                 margin:0 auto; padding:5px;">
<canvas id    = "canvasArea"
        width = "300"  height = "125"
        style = "border:2px solid black">
Your browser doesn't currently support HTML5 Canvas.
</canvas>
</div>
</body>
</html>

Related Topic