will
will

Reputation: 4575

How can I fill a polygon with a texture using svg?

I'm currently using svg.js - but I am very welcome to alternative suggestions - is there any way I can create a polygon and then apply a repeating texture to it?

Below is an example of what I am attempting to achieve. Here is a jsFiddle which shows my best attempt. This works, but the image doesn't repeat so if you increase the size of the polygon the effect is lost.

I'm creating an image, and then two polygons. One for the shape and another for the shadow. I then mask the image with the polygon.

image.maskWith(polygon.fill({color: '#FFF'}));

The idea is that instead of creating many different shaped, coloured and textured PNG's we will be able to create one texture and use svg.js to adjust everything else.

Thanks in advance :)

Example of polygon with texture

Upvotes: 6

Views: 6100

Answers (2)

wout
wout

Reputation: 2567

Svg.js has a pattern plugin. Usage is very simple:

var pattern = draw.pattern(20, 20, function(add) {
  add.image(20, 20)
})

var circle = draw.circle(200).fill(pattern)

I only need to mention that patterns in Opera sometimes render black. I still need to find out why that is.

UPDATE:

The latest release of svg.js (1.0.0-rc.4) supports direct a fill with an image url or image instance:

var circle = draw.circle(200).fill('/path/to/image.jpg')

More info here: http://documentup.com/wout/svg.js#syntax-sugar/fill

Upvotes: 2

Michael Mullany
Michael Mullany

Reputation: 31715

This is what the <pattern> element in SVG is for. Mozilla documentation.

Upvotes: 9

Related Questions