HTML and CSS Reference
In-Depth Information
To multiply the current canvas context transformation with a matrix, call:
context.transform(a, b, c, d, dx, dy);
If the matrix elements are all stored in an array, it can be handy to apply the entire array as arguments:
context.transform.apply(context, [a, b, c, d, dx, dy]);
If there haven't been any transformations, then it's assumed we're using an identity matrix or a null
transform. This matrix is described as:
1 0 0
0 1 0
0 0 1
Multiplying this matrix does nothing to the transformation. So, if you ever want to reset the canvas context,
set its transformation to an identity matrix, like so:
context.setTransform(1, 0, 0, 1, 0, 0);
But back to the components of a matrix, what do all these letters mean? Well, dx and dy control the
position of the canvas context by translating it on the x and y axis—remember coordinate 0, 0 is at the top-
left corner. The a , b , c , and d positions in the matrix are a little trickier because they are so dependent on
each other. If you set b and c to 0, you can use a and d to scale the object on the x and y axis. If you set a
and d to 1, you can use b and c to skew the object on the y and x axis. And, you can use a , b , c , and d
together in a way that you'll find familiar when laid out like this:
cos -sin dx
sin cos dy
u v w
This contains a rotation matrix. Naturally, cos and sin refer to the cosine and sine of an angle (in radians)
that you wish to rotate the canvas context by. Let's try that one out in the next example, 02-matrix-
rotate.html , which draws a red box in the animation loop:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Matrix Rotate</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
angle = 0;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
 
Search WWH ::




Custom Search