Is it possible to ‘fill’ a shape on an HTML5 canvas with an image instead of a color?
I’ve drawn a bunch of shapes (squares with various corners sliced off at 45 degree angles). I’d like to be able to ‘fill’ these shapes with an image, instead of a color. At the moment I’ve got a line stating:
context.fillStyle = '#123456' // example fill color
What I’m looking for is something like:
context.fillStyle = 'url(http://www.myimagereference.com/image.png)';
I know that I can’t use fillStyle this way – but is there another way to achieve this kind of thing?
You can do this by defining a clipping region that is the same as your shape and then using
drawImage()to draw into this region; then stroke (only) your path on top of this.I’ve created an example of this technique for you on my website:
http://phrogz.net/tmp/canvas_image_as_background_to_shape.html
Here’s the relevant code; it proportionately scales the image to fill the width you specify:
It’s up to you to modify that if you want tiling, or asymmetric stretching, low-opacity tinting, etc. Here’s how you might use it:
Note that when you create your image to pass to the function, you must set its
onloadhandler before setting thesrc: