In this recipe, we'll rotate an image by translating and rotating the canvas context, and then drawing an image on the transformed context.
Follow these steps to rotate an image:
Define a canvas context:
window.onload = function(){ var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d");
Create a new
image
object and set itsonload
property:var imageObj = new Image(); imageObj.onload = function(){
When the image loads, translate the context to the center of the canvas, rotate the context by 45 degrees counter-clockwise, and then draw the image:
// translate context to center of canvas context.translate(canvas.width / 2, canvas.height / 2); // rotate context by 45 degrees counter clockwise context.rotate(-1 * Math.PI / 4); context.drawImage(this, -1 * imageObj.width / 2, -1 * imageObj.height / 2); };
Set the source of the image:
imageObj.src = "jet_300x214.jpg...