Last active
February 23, 2023 20:56
-
-
Save geoffb/6392450 to your computer and use it in GitHub Desktop.
A simple example of rotating a rectangle using HTML5 canvas.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Thnx worked for me
Very helpful!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!