Canvas is a interesting feature in HTML5. Nowadays many developers use canvas to create powerful web applications. By definition canvas is “a resolution-dependent bitmap canvas which can be used for rendering graphs, game graphics, or other visual images on the fly”. Canvas allow us to draw graphics using javascript. When we use canvas there is no need to install browser plug-ins like flash player. We can draw many shapes using properties in canvas. Currently canvas support 2D surface.
We can create a canvas in the browser using following code
<canvas id=”myCanvas” style=”width:300px; height:300px”></canvas>
This canvas will be invisible also canvas have x and y coordinates. Using following code we can get context of canvas.
var myCanvas = document.getElementById(“myCanvas”)
var context = myCanvas.getContext(“2d”)
Transformation functions
- scale – allows you to scale the current context.
- rotate – allows you to rotate the x and y coordinates of the current context.
State functions
- save – allows you to save the current state of the context.
- restore – allows you to restore the state of the context from a previously saved state.
Transformations &Animations
When the context is created, the transformation matrix must initially be the identity transform. It may then be adjusted using the transformation methods.
- scale(x, y) – changes the scaling transformation with the given characteristics
- rotate(angle) – changes the transformation matrix to apply a rotation transformation with the given characteristics
- translate(x, y) – changes the transformation matrix to apply a translation transformation with the given characteristics
- transform(m11, m12, m21, m22, dx, dy) – changes the transformation matrix to apply the matrix given by the arguments
- setTransform(m11, m12, m21, m22, dx, dy) – changes the transformation matrix to the matrix given by the arguments.
Transformations and animations can work separately. Let’s observe how is the rotation. To rotate the context, pass in an angle and it will rotate on the canvas. The following example demonstrates draws a rectangle every 250 milliseconds and each rectangle is rotated, so the effect is like a spinning wheel.
var can = function () {
var canvas;
var context;
return {
draw: function () {
var r = Math.floor(Math.random() * 255) + 70;
var g = Math.floor(Math.random() * 255) + 70;
var b = Math.floor(Math.random() * 255) + 70;
var s = ‘rgba(‘ + r + ‘,’ + g + ‘,’ + b + ‘, 0.5)’;
context.rotate(0.2 * Math.PI);
context.fillStyle = s;
context.fillRect(10, 0, 150, 50);
},
init: function () {
canvas = document.getElementById(“myCanvas”);
context = canvas.getContext(“2d”);
context.translate(200, 250);
setInterval(can.draw, 250);
}
}
} ();
window.onload = can.init;
The output will be like this..
