Welcome to Blogs @ Andrew Qu
Blog Index
All blogs
Search results

Setting HTML 5 Canvas Transformation Matrix

Sumamry

Shows how to set the HTML5 canvas transformation matrix directly to increase performance.

The Sample Task

Assume we have an image file. We want to draw the image on the target canvas by applying scale factors, a rotation angle and a translation. This is shown in the following diagram:

  • The source image width = Ws, height = Hs. This is scaled to Wd and Hd.
  • The image is then rotated by angle a.
  • Finally, it is translated by (Xt,Yt) to the final position.


The Canvas Transformation

HTML 5 provides various transformation APIs. The above transformation can be achieved via these calls:

var context = document.getElementById('canvas').getContext('2d');
context.save();
 
context.scale(Wd / Ws, Hd / Hs);
context.rotate(a);
context.translate(Xt, Yt);
 
context.drawImage(img, 0, 0);
context.restore();
HTML 5 also provides an API that sets the transformation matrix directly context.setTransform(a, b, c, d, e, f); where

 

Using this API, the calls to scale(), rotate(), translate() can be combined into a single call:
var vcos = Math.cos(a);
var vsin = Math.sin(a);
context.setTransform(xs * vcos, xs* vsin, -ys * vsin, ys * vcos, Xt, Yt);


Performance Test

A simple test of 10,000 operations indicate that the setTransform() method is 5 times as fast. The test was run in 64bit IE10 browser on a PC. The performance gain would be noticeable on mobile devices.

Call methodElapse Time
setTransformation()10 ms
Scale(), rotate(), translate()51 ms


The Algebra

[Translation] x [Rotation] x [Scaling] = [Final result]

*** END ***
Ads from Google
Dr Li Anchor Profi
www.anchorprofi.de
Engineering anchorage plate design system
©Andrew Qu, 2015. All rights reserved. Code snippets may be used "AS IS" without any kind of warranty. DIY tips may be followed at your own risk.