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. Let's add some colour and 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 (for
example, RGB, hex, RGBA, and so on), fillStyle and strokeStyle
also accept gradients and patterns generated using the 2D API.
FIguRE 5.5 Using fill styles
and rectangle strokes.
NoTE querySelector
and querySelectorAll
are new DOM methods that
accept a CSS selector and return
the elements it matches. Currently
available in all the latest browsers,
querySelector returns the
first DOM node it finds, whereas
querySelectorAll returns a
NodeList object that you'll need
to iterate over.
Painting gradients and patterns
Using the context object, you can generate 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, 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 using video as
a source isn't yet implemented at the time of writing).
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