How to rotate object in HTML5 Canvas

This airticle explains how to rotate object (rotation transformation) in HTML5 Canvas.

Object Rotation in HTML5 Canvas

Open with new tab

Source


      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
      <title>Object rotation in html5 canvas - Nibunan</title>
      </head>
      <body style="margin: 0px">
      <canvas width="700" height="460" id="drawing-surface"></canvas>
      <script type="text/javascript">
      var canvas = document.getElementById("drawing-surface");
      var drawingSurface = document.getElementById("drawing-surface").getContext("2d");
      function getRadialGradient() {
      var grdient = drawingSurface.createRadialGradient(430, 220, 1, 430, 220, 250);
      grdient.addColorStop(0, "rgb(255,255,255)");
      grdient.addColorStop(1, "rgb(255,200,0)");
      return grdient;
      }
      function drawArc(cx, cy, radius, startAngle, endAngle) {
      startAngle = startAngle * (2 / 360);
      endAngle = endAngle * (2 / 360);
      drawingSurface.arc(cx, cy, radius, startAngle * Math.PI, endAngle * Math.PI, false);
      }
      function drawBezierCurve(points) {
      for (var i = 0; i < points.length; i += 3) {
      drawingSurface.bezierCurveTo(points[i].x, points[i].y, points[i + 1].x, points[i + 1].y, points[i + 2].x, points[i + 2].y);
      }
      }
      function drawEye() {
      drawingSurface.fillStyle = "white";
      drawingSurface.beginPath();
      drawArc(260, 170, 10, 0, 360);
      drawingSurface.fill();
      drawingSurface.stroke();
      }
      function drawObject(rotate) {
      drawingSurface.restore();
      drawingSurface.strokeStyle = 'black';
      drawingSurface.fillStyle = getRadialGradient();
      drawingSurface.lineWidth = 3;
      drawingSurface.beginPath();
      if (rotate) {
      drawingSurface.save();
      drawingSurface.translate(300, -150);
      drawingSurface.rotate(Math.PI / 4);
      drawingSurface.globalAlpha = 1;
      }
      else {
      drawingSurface.globalAlpha = 0.3;
      }
      drawingSurface.moveTo(120, 200);
      drawBezierCurve([
      { x: 130, y: 200 },
      { x: 200, y: 220 },
      { x: 200, y: 200 }
      ]);
      drawArc(270, 180, 70, 180, 30);
      drawBezierCurve([
      { x: 300, y: 250 },
      { x: 500, y: 250 },
      { x: 500, y: 220 },
      { x: 550, y: 400 },
      { x: 450, y: 400 },
      { x: 300, y: 400 },
      { x: 250, y: 400 },
      { x: 150, y: 400 },
      { x: 200, y: 230 },
      { x: 150, y: 240 },
      { x: 100, y: 240 },
      { x: 120, y: 200 }
      ]);
      drawingSurface.closePath();
      drawingSurface.fill();
      drawingSurface.stroke();
      drawEye();
      }
      drawObject(false);
      drawObject(true);

      </script>
      </body>
      </html>