Canvas JavaScript

Transformations - Moving Arm

This JavaScript program demonstrates how to draw a moving arm with rectangles with transformations on a canvas element.

TransformationsMovingArm.html

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net's Javascript</title>
    <script type="text/javascript" src="TransformationsMovingArm.js"></script>
  </head>
  <body onload="Initialize()">
     <canvas id="idCanvas" width="600" height ="600" style="background-color: #F0F0F0;"></canvas>
  </body>
</html>

TransformationsMovingArm.js

var gqCanvas = null;
var gqContext = null;
var giTick = 0;
const gkiMaxTick = 50;
var giIncrement = 1;

function Initialize() {
  gqCanvas = document.getElementById("idCanvas");
  gqContext = gqCanvas.getContext("2d");
  Advance();
}

function Draw() {
	// Reset the transform to prevent accumulation
	gqContext.setTransform(1, 0, 0, 1, 0, 0);
  // Clear the whole canvas
  gqContext.clearRect(0, 0, gqCanvas.width, gqCanvas.height);
  // The animations of the rectangles will be slightly different
  var dT = giTick/gkiMaxTick;
  // Draw a red rectangle on the context
  gqContext.fillStyle = '#FF8080';
  // Draw the upper arm
  // Translate to the center of rotation, rotate, and then translate back
  gqContext.translate(300, 300);
  gqContext.rotate(dT*Math.PI/4.0);
  gqContext.translate(0, -300);
  gqContext.fillRect(0, 280, 100, 40);
  // Draw the forearm
  gqContext.translate(100, 300);
  gqContext.rotate(dT*Math.PI/2.0);
  gqContext.fillRect(0, -15, 150, 30);
  // Draw the hand
  gqContext.translate(150, 0);
  gqContext.rotate(dT*Math.PI/3.0);
  gqContext.fillRect(0, -25, 50, 50);
}

function Advance() {
	giTick = giTick + giIncrement;
  // This can be used to set the direction.
  if (giTick == gkiMaxTick || giTick == 0) {
  	giIncrement = -giIncrement;
  }
  Draw();
  setTimeout(Advance, 50);
}
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.