Combining Scale and Rotation Transformations

If we want to both scale and rotate an object, Canvas transformations can easily be combined to achieve the desired results (as shown in Figure 2-20). Let’s look in Example 2-12 at how we might combine them by using scale(2,2) and rotate(angleInRadians) from our previous examples.

Example 2-12. Scale and rotation combined

function drawScreen() {
      context.setTransform(1,0,0,1,0,0);
      var angleInRadians = 45 * Math.PI / 180;
      var x = 100;
      var y = 100;
      var width = 50;
      var height = 50;
      context.translate(x+.5*width, y+.5*height);
      context.scale(2,2);
      context.rotate(angleInRadians);
      context.fillStyle = "red";
      context.fillRect(-.5*width,-.5*height , width, height);

   }
Scale and rotation combined

Figure 2-20. Scale and rotation combined

Example 2-13 also combines rotation and scale, this time using a rectangle. Figure 2-21 reveals what it creates.

Example 2-13. Scale and rotate a nonsquare object

function drawScreen() {

      //now draw a red rectangle
      context.setTransform(1,0,0,1,0,0);
      var angleInRadians = 90 * Math.PI / 180;
      var x = 100;
      var y = 100;
      var width = 100;
      var height = 50;
      context.translate(x+.5*width, y+.5*height);
      context.rotate(angleInRadians);
      context.scale(2,2);

      context.fillStyle = "red";
      context.fillRect(-.5*width,-.5*height , width, height);

   }
Scale and rotate a nonsquare object

Figure 2-21. Scale and rotate ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.