HTML and CSS Reference
In-Depth Information
The arguments to fillRect are x, y, width, and height. The x and
y coordinates start in the top left. As shown in Figure 5.4, the
default colour is black. Add some colour and also draw an out-
line around the canvas so that the canvas looks like figure 5.5 :
ctx.fillStyle = 'rgb(0, 255, 0)';
ctx.fillRect(10, 20, 50, 50); // creates a solid square
ctx.strokeStyle = 'rgb(0, 182, 0)';
ctx.lineWidth = 5;
ctx.strokeRect(9, 19, 52, 52); // draws an outline
In the previous code listing, you're drawing twice on the canvas:
once with fillRect and once with strokeRect . When you're not
drawing, you're setting the colour and style of the 2D context
which must happen before the fill or stroke happens, otherwise
the default colour of black is used. Along with CSS colours
being used in the fillStyle and strokeStyle (for example, RGB,
hex, RGBA, and so on), you can also use gradients and patterns
generated using the 2D API.
fIgure 5.5 Using fill styles
and rectangle strokes.
tIp The entire coordi-
nates system in the 2D
drawing API works in the same
way CSS coordinates work, in
that you work from the top-left
to the bottom-right.
painting gradients and patterns
Using the context object, you can generate a fill style that can
be a linear gradient, radial gradient, or a pattern fill, which in
turn can be used as the fillStyle on the canvas. Gradients and
radial gradients work similar to CSS gradients (currently avail-
able in WebKit and Firefox 3.6), in that you specify a start point
and colour stops for the gradient.
Patterns, on the other hand, allow you to point to an image
source and then specify how the pattern should repeat, again
similar to the repeat process on a CSS background image. What
makes createPattern really interesting is that the image source
can be an image, another canvas, or a video element (though at
time of writing, using video as a source isn't implemented yet).
Creating a simple gradient is easy and possibly even faster than
starting up Photoshop:
var canvas = document.querySelector('canvas'),
ctx = canvas.getContext('2d'),
gradient = ctx.createLinearGradient(0, 0, 0, canvas.
¬ height);
gradient.addColorStop(0, '#fff');
gradient.addColorStop(1, '#000');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
Search WWH ::

Custom Search