Rotating an Image using the Canvas Element
In this example we show how to rotate an image around its center point in HTML5. Like the Simple Animation example we create a javascript loop and draw our image each iteration.
<body onload="drawCanvas();">
<div>
<canvas id="myCanvas" width="30" height="30">
<p>Your browser doesn't support canvas.</p>
</canvas>
</div>
</body>
In our code we create a loop and render our image at the current rotation angle. When we finish rendering we increment the angle by 1.
var surface;
var happy;
var angle = 0;
function drawCanvas() {
// Get our Canvas element
surface = document.getElementById("myCanvas");
if (surface.getContext) {
// If Canvas is supported, load the image
happy = new Image();
happy.onload = loadingComplete;
happy.src = "images/happy.png";
}
}
function loadingComplete(e) {
// When the image has loaded begin the loop
setInterval(loop, 25);
}
function loop() {
// Each loop we rotate the image
// Grab the context
var surfaceContext = surface.getContext('2d');
// Clear the canvas to White
surfaceContext.fillStyle = "rgb(255,255,255)";
surfaceContext.fillRect(0, 0, surface.width, surface.height);
// Save the current context
surfaceContext.save();
// Translate to the center point of our image
surfaceContext.translate(happy.width * 0.5, happy.height * 0.5);
// Perform the rotation
surfaceContext.rotate(DegToRad(angle));
// Translate back to the top left of our image
surfaceContext.translate(-happy.width * 0.5, -happy.height * 0.5);
// Finally we draw the image
surfaceContext.drawImage(happy, 0, 0);
// And restore the context ready for the next loop
surfaceContext.restore();
// Increment our rotation angle
angle++;
}
function DegToRad(d) {
// Converts degrees to radians
return d * 0.0174532925199432957;
}
In the code above there seems to be an awful lot happening in the main loop. This is to ensure the rotation occurs around the center point of our image.
The completed example:
Rotating the Image around the Top-Left Point
If you wanted to rotate around the top-left point of your image then the main loop would look like this:
function loop() {
// Each loop we move the image by altering its x/y position
// Grab the context
var surfaceContext = surface.getContext('2d');
// Clear the canvas to White
surfaceContext.fillStyle = "rgb(255,255,255)";
surfaceContext.fillRect(0, 0, surface.width, surface.height);
// Save the current context
surfaceContext.save();
// Perform the rotation
surfaceContext.rotate(DegToRad(angle));
// Finally we draw the image
surfaceContext.drawImage(happy, 0, 0);
// And restore the context ready for the next loop
surfaceContext.restore();
// Increment our rotation angle
angle++;
}
In the above code because we are not rotating around any particular point we do not need to do the translation before and after the rotation.
Rate this:
1 Star
2 Star
3 Star
4 Star
5 Star
48 Ratings / 3.9 Average