简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM