HTML and CSS Reference
In-Depth Information
To c r e a t e t h e e f e c t s h To w in i in Figure 5.8 (a tiled image across
the back of the canvas), stretch the canvas over the size of the
window. Then dynamically create an image and when it fi res the
load event, use the image as the source of a repeating pattern:
var canvas = document.querySelector('canvas'),
img = document.createElement('img'),
ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
img.onload = function () {
ctx.fillStyle = ctx.createPattern(this, 'repeat');
ctx.fillRect(0, 0, canvas.width, canvas.height);
img.src = 'remysharp_avatar.jpg';
FIGURE 5.8 Tilling an
image on a canvas using the
createPattern method.
In this example I've created an image on the fl y using document.
createElement , only once the onload event fi res do I continue to
and build the pattern fi ll. You need to wait until all the data has
loaded in to the image before you can begin to use it.
Now that the image is loaded, I'm able to set the fillStyle
using createPattern . I've used createPattern(this, 'repeat') ,
and this refers to the image that fi red the load event, but I
can just as easily use another canvas as the source. The string
'repeat' follows the same syntax as CSS background-repeat , in
that repeat-x , repeat-y , and no-repeat also work.
Search WWH ::

Custom Search