Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 550
will Avatar asked Sep 25 '13 15:09

will


People also ask

How do you make a SVG polygon?

To draw a polygon in HTML SVG, use the SVG <polygon> element. The <polygon> element creates a graphic containing at least three sides. The points attribute is the x and y coordinates for each corner of the polygon.

How do SVG polygon points work?

For <polygon> , points defines a list of points, each representing a vertex of the shape to be drawn. Each point is define by a X and Y coordinate in the user coordinate system. Note: A polygon is a closed shape, meaning the last point is connected to the first point.

What is SVG create star using SVG?

SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG. To draw a polygon in HTML SVG, use the SVG <polygon> element.

What is SVG polygon?

SVG Polygon - <polygon>The <polygon> element is used to create a graphic that contains at least three sides. Polygons are made of straight lines, and the shape is "closed" (all the lines connect up). Polygon comes from Greek. "Poly" means "many" and "gon" means "angle".


2 Answers

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

like image 175
Michael Mullany Avatar answered Nov 07 '22 09:11

Michael Mullany


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

like image 28
wout Avatar answered Nov 07 '22 07:11

wout