Skip to content

Instantly share code, notes, and snippets.

@geoffb
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>
<html>
<head>
<title>HTML5 Canvas Transformation</title>
</head>
<body>
<script>
// Create our canvas and append it to the document body
var stage = document.createElement("canvas");
stage.width = 320;
stage.height = 240;
document.body.appendChild(stage);
// 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
ctx.save();
// 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
ctx.restore();
</script>
</body>
</html>
@MartinJaskulla
Copy link

Very helpful!

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