This JavaScript program demonstrates how to draw rotating rectangles with transformations on a canvas element.
<!DOCTYPE html> <html> <head> <title>XoaX.net's Javascript</title> <script type="text/javascript" src="TransformationsRotatingRectangles.js"></script> </head> <body onload="Initialize()"> <canvas id="idCanvas" width="600" height ="600" style="background-color: #F0F0F0;"></canvas> </body> </html>
var gqCanvas = null; var gqContext = null; var giTick = 0; const gkiMaxTick = 50; function Initialize() { gqCanvas = document.getElementById("idCanvas"); gqContext = gqCanvas.getContext("2d"); Advance(); } function Draw() { // 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; // Reset the transform to prevent accumulation gqContext.setTransform(1, 0, 0, 1, 0, 0); // Draw a red rectangle on the context gqContext.fillStyle = '#FF8080'; // Translate to the center of rotation, rotate, and then translate back gqContext.translate(300, 300); gqContext.rotate(dT*2.0*Math.PI); gqContext.translate(-300, -300); gqContext.fillRect(200, 280, 200, 40); // Reset the transform to prevent accumulation gqContext.setTransform(1, 0, 0, 1, 0, 0); // Draw a second gray rectangle on the context gqContext.fillStyle = '#808080'; gqContext.translate(300, 300); gqContext.rotate(-dT*2.0*Math.PI); gqContext.translate(-300, -300); gqContext.fillRect(200, 280, 200, 40); } function Advance() { // This can be used to set the direction. giTick = ((giTick + 1) % gkiMaxTick); Draw(); setTimeout(Advance, 50); }
© 20072025 XoaX.net LLC. All rights reserved.