HTML and CSS Reference
In-Depth Information
Affine Transformations
Canvas has several other useful transform APIs, such as clipping, drawing text, and an affine transformation. An affine
transformation uses parallel and linear translation. Using affine transformations, you can transform shapes and
images on a HTML5 canvas. An affine transformation is of special importance when you create Canvas-based games.
You should understand the basics of matrix math if you utilize affine transformations extensively, but there
are some helper APIs to make for easier usage: translate, rotate, and scale. You can stack the effects. There are few
disadvantages to using transformations; you can use them freely.
Listing 16-4 shows an image that is rotated 30 degree, scaled 1/2, and translated (100px, 100px) in the
transformed coordinates (see Figure 16-4 ). Affine transformations are the only way to transform images like this.
Listing 16-4. Simple Transform
onload = function() {
var img = document.createElement("img");
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = canvas.height = 300;
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
ctx.rotate(30 * Math.PI / 180);
ctx.scale(0.5, 0.5);
ctx.translate(100, 100);
ctx.drawImage(img, 0, 0);
};
img.src = "lenna.jpg";
};
Figure 16-4. Simple transform output
Generally, when you scale, rotate, and translate images with the anchor point at (ax, ay), you should transform in
the order corresponding to translate, rotate, scale, and translate(-ax, -ay), as shown in Listing 16-5 and Figure 16-5 .
Listing 16-5. Transform Example
onload = function() {
var img = document.createElement("img");
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = canvas.height = 300;

Search WWH ::

Custom Search