cdub
cdub

Reputation: 25741

Add a background image to an SVG

I am using Snap.svg and trying to add a background image to a polygon.

The polygon is as follows:

<svg id="test" height="600" width="600" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="" class=""></svg>

var polygon = s.polyline(200, 286, 250, 200, 350, 200, 400, 286, 350, 373, 250, 373);

I have tried a bunch of different ways to make the background image but none of them work:

polygon.attr(
{
    fill: 'url(http://csshexagon.com/img/meow.jpg)'
});


polygon.attr('xlink:href', 'url(http://csshexagon.com/img/meow.jpg)');

Any ideas? Thanks.

Upvotes: 0

Views: 695

Answers (1)

Ian
Ian

Reputation: 13852

There's a couple of bits you need to do. If using Snap, make sure you are using the latest version, so 'toPattern()' works.

Then we can draw the image, convert it to a pattern, and then fill the polygon with the pattern.

var polygon = paper.polyline(200, 286, 250, 200, 350, 200, 400, 286, 350, 373, 250, 373);
var img = paper.image('https://i.imgur.com/LQIsf.jpg', 150, 200, 250, 250)
var p = img.toPattern( 0,0,400,400 );
polygon.attr({ fill: p })

jsfiddle

Upvotes: 2

Related Questions