Skip to content

Instantly share code, notes, and snippets.

Last active February 23, 2023 20:56
Show Gist options
  • Save geoffb/6392450 to your computer and use it in GitHub Desktop.
Save geoffb/6392450 to your computer and use it in GitHub Desktop.
A simple example of rotating a rectangle using HTML5 canvas.
<!DOCTYPE html>
<title>HTML5 Canvas Transformation</title>
// Create our canvas and append it to the document body
var stage = document.createElement("canvas");
stage.width = 320;
stage.height = 240;
// Grab a reference to the canvas' 2D context
var ctx = stage.getContext("2d");
// Paint a background color
ctx.fillStyle = "cornflowerblue";
ctx.fillRect(0, 0, stage.width, stage.height);
// Draw a non-transformed red rectangle on the left
ctx.fillStyle = "red";
ctx.fillRect(40, 80, 80, 80);
// Now, let's draw a rotated yellow rectangle on the right
// First, let's save our canvas context in order to easily restore
// it after our transformations;
// Next, we'll translate (move the origin) to the center
// of where we'll be drawing the rectangle
ctx.translate(240, 120);
// Any transformations applied from here on out will be
// relative to the origin of 240, 120
// Note that we're using radians, not degrees to specify rotation
ctx.rotate(Math.PI / 4); // 45 degrees
// If we desired to scale the rectangle as well, we'd do that here:
// ctx.scale(1.5, 1.5); // 1.5x normal size on both the x and y axis
// Now we're ready to draw our rectangle
// The diffence this time is that our coordinates are relative
// to the origin, just like the .rotate call
ctx.fillStyle = "yellow";
ctx.fillRect(-40, -40, 80, 80);
// Finally, we restore our canvas context so that subsquent draws
// are not transformed
Copy link

Thanks for this example! I was having tons of trouble figuring out why my rectangle was not rotating in place and it was because no other guide I read mentioned that you need to keep in mind that you ran a transform on the context and you need to adjust to draw for the new context. Hour of confusion solved by reading your comments. Keep up the good work!

Copy link

Thnx worked for me

Copy link

Very helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment