HTML and CSS Reference
In-Depth Information
context.clearRect(0, 0, canvas.width, canvas.height);
angle += 0.03;
var cos = Math.cos(angle),
sin = Math.sin(angle),
dx = canvas.width / 2,
dy = canvas.height / 2;
context.save();
context.fillStyle = "#ff0000";
context.transform(cos, sin, -sin, cos, dx, dy);
context.fillRect(-50, -50, 100, 100);
context.restore();
}());
};
</script>
</body>
</html>
Here you have an angle variable that increases on each frame. We find the sine and cosine of that angle
and feed them to the context.transform method, in the way specified for rotation. We also apply a
translation based on the canvas width and height, centering the rectangle. Test this and you have a
spinning box.
In the drawFrame function, we wrapped the rectangle drawing code within calls to context.save and
context.restore . These methods are used to save and retrieve the canvas drawing state, which is
basically a snapshot of all the styles and transformations that have been applied. By using these, we can
traverse through multiple matrix transformations by pushing and popping to the stack. You can nest
multiple save and restores; just be mindful of which transformation you're working on. If you ever need to
reset the canvas context, just set an identity matrix.
To demonstrate something a little more practical, we look at skewing. Skewing means stretching
something out on one axis so that one part goes one way and the other part goes the other way. Think of
italic letters and the way they slope; this is like a skew. The top part of the letters goes to the right and the
bottom part to the left. This is something that can be tricky to implement using formulas, but is easy when
applying a transformation matrix. As mentioned previously, you set a and d of the matrix to 1, and the b
value is the amount to skew on the y-axis, and c controls the skew on the x-axis. Let's try an x skew first.
In 03-skew-x.html , we used almost the exact same setup as the last example, but since we're using the
mouse position, make sure you include our helpful utility function at the top of the script:
var mouse = utils.captureMouse(canvas);
Now change how the matrix is applied in the drawFrame function:
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var skewX = (mouse.x - canvas.width / 2) * 0.01,
dx = canvas.width / 2,
dy = canvas.height / 2;
 
Search WWH ::




Custom Search