6

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

will
  • 4,557
  • 6
  • 32
  • 33
  • 1
    After reading the documentation : http://documentup.com/wout/svg.js. I think it's not possible with js method. And I haven't solution with CSS.. Maybe add pattern image in a loop. – Donovan Charpin Sep 25 '13 at 15:32
  • I had a good look through as well, ahh well - do you know of any other libraries that are capable? – will Sep 25 '13 at 15:47
  • When I work with SVG, I create the SVG file with illustrator and after I work with tags which are created in generation. – Donovan Charpin Sep 25 '13 at 16:18
  • The problem with that is that these content areas could be any height, and using an SVG created in Illustrator and applying it as a background image stretches everything, including shadows and textures. – will Sep 25 '13 at 16:25
  • I know this is old, but have you looked at Raphael (https://en.wikipedia.org/wiki/Rapha%C3%ABl_%28JavaScript_library%29)? It converts javascript commands into SVG and has a fill command. – Mark Manning Aug 04 '16 at 01:15

2 Answers2

9

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

Michael Mullany
  • 30,283
  • 6
  • 81
  • 105
2

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

wout
  • 2,477
  • 2
  • 21
  • 32