HTML and CSS Reference
In-Depth Information
Drawing shapes
To draw on the canvas, you need to get a drawing context. The context
then gives you access to methods that allow the drawing of lines and
shapes.
Basic shapes are easy. If you replace the
previous draw() function, you can draw
a rectangle by using the fillRect
method. The only prerequisite is that
you first set the fill color using the
fillStyle method. You call the fillRect
method with four arguments: the x and
y values of the upper-left corner and the
width and height to fill:
function draw() {
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(255,0,0)';
ctx.fillRect(50,50,100,100);
}
}
In addition to fillRect() , there are also methods to clear an area of
pixels and to draw an empty rectangle: clearRect() and strokeRect(),
respectively. They take the same parameters as fillRect() .
Let's extend the code to draw a line. Lines are a little more complex.
You have to first draw a path, but the path doesn't appear until you
apply a stroke. If you've ever used graphics software like Photoshop,
this process should be familiar to you.
Search WWH ::




Custom Search