Rotating an Image on a Canvas using HTML5

This article describes how to rotate images using JavaScript and HTML5.
It's not as simple as just "rotating an image". It's more like rotating the canvas, then set the image's orientation, then resetting the canvas.
In this example, I will show how to rotate an image around its center point in HTML5.
NOTE: It is important to remember that in canvas, the last transformation that you write is executed first. So if you are doing many transformations then you must write them in reverse order.
Step 1
Load the image using the following:
Note: To check that the image has loaded completly:
image.readyState == 'complete'
Step 2-
Since I created the canvas dynamically, ensure to insert it into the document before calling: "canvas.getContext('2d');".
Step 3
Example :
  1. <!DOCTYPE html>
  2. <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta charset="utf-8" />
  5. <script type="application/javascript">
  6. var surface;
  7. var image;
  8. var angle = 0;
  9. function drawCanvas()
  10. {
  11. // Get our Canvas element
  12. surface = document.getElementById("myCanvas");
  13. if (surface.getContext)
  14. {
  15. // If Canvas is supported, load the image
  16. image = new Image();
  17. image.onload = loadingComplete;
  18. image.src = "C:\Users\Public\Pictures\Sample Pictures\Tulips.jpg";
  19. }
  20. }
  21. function loadingComplete(e)
  22. {
  23. // When the image has loaded begin the loop
  24. setInterval(loop, 25);
  25. }
  26. function loop()
  27. {
  28. // Each loop we rotate the image
  29. var surfacesurfaceContext = surface.getContext('2d');
  30. // Clear the canvas to White
  31. surfaceContext.fillStyle = "#ffffff";
  32. surfaceContext.fillRect(0, 0, surface.width, surface.height);
  33. // Save the current context
  34. surfaceContext.save();
  35. // Translate to the center point of our image
  36. surfaceContext.translate(image.width * 0.5, image.height * 0.5);
  37. // Perform the rotation
  38. surfaceContext.rotate(DegToRad(angle));
  39. // Translate back to the top left of our image
  40. surfaceContext.translate(-image.width * 0.5, -image.height * 0.5);
  41. // Finally we draw the image
  42. surfaceContext.drawImage(image, 0, 0);
  43. // And restore the context ready for the next loop
  44. surfaceContext.restore();
  45. angle++;
  46. }
  47. function DegToRad(d)
  48. {
  49. // Converts degrees to radians
  50. return d * 0.01745;
  51. }
  52. </script>
  53. <title>Rotating an inage on canvas<title>
  54. </head>
  55. <body onload="drawCanvas();">
  56. <div>
  57. <canvas id="myCanvas" width="30" height="30">
  58. <p>Your browser doesn't support canvas.</p>
  59. </canvas>
  60. </div>
  61. </body>
  62. </html>
Output
rotate1.jpg
rot.jpg
rota.jpg
rotat.jpg