HTML and CSS Reference
In-Depth Information
To use the image pattern, apply it to the
fillColor
and
strokeColor
properties of the
context, just as you would apply a color:
context.fillStyle = pattern;
or:
context.strokeStyle = pattern;
For example, to load an image named
texture.jpg
and apply it to the
fillStyle
so that
it tiles on both the x and y axes, you would write code like this:
var pattern = new Image();
pattern.src = "texture.jpg"
pattern.onload = function() {
var pattern = context.createPattern("texture.jpg", "repeat");
context.fillStyle = pattern;
...
}
Patterns with Video: The Bad News
The HTML5 Canvas API specifies that an HTML5
video
element can be used as the
source for
createPattern()
instead of an image. However, all of our attempts to do so
emitted the following JavaScript error:
Uncaught Error: TYPE_MISMATCH_ERR: DOM Exception 17
According to the DOM reference at
www.gnu.org
,
DOM Exception 17, TYPE
_MISMATCH_ERR occurs “if the type of an object is incompatible with the expected
type of the parameter associated to the object.”
So it appears that most browsers have not included support for using video as the
pattern for
createPattern()
. However, you can still load and play video on Canvas,
which we will discuss in depth in
Chapter 6
.
Handling Gradients and Patterns in Text Arranger
Text Arranger 3.0 includes many changes that were implemented to support using
gradients and image patterns with text on HTML5 Canvas. To see these changes in
action, we first need to make sure that we have preloaded the
texture.jpg
image, which
we will use for the
context.createPattern()
functionality. To do this, we will create a
new function named
eventAssetsLoaded()
that we will set as the event handler for the
onload
event of the
Image
object that will hold the pattern. When that image has loaded,
we will call
canvasApp()
in the same way we called it from
eventWindowLoaded()
:
function eventWindowLoaded() {
var pattern = new Image();
pattern.src = "texture.jpg";
pattern.onload = eventAssetsLoaded;
}