简体   繁体   English

将背景图像添加到SVG

[英]Add a background image to an SVG

I am using Snap.svg and trying to add a background image to a polygon. 我正在使用Snap.svg并尝试将背景图像添加到多边形。

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. 如果使用的是Snap,请确保使用的是最新版本,以便“ toPattern()”有效。

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 jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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