jQuery 如何设置 SVG 矩形元素的背景图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10736946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:41:54  来源:igfitidea点击:

How to set a SVG rect element's background image?

jquerypluginssvg

提问by tmaster

I created a SVG rect using keith-wood's jQuery SVG plugin. Here is the code:

我使用 keith-wood 的 jQuery SVG 插件创建了一个 SVG 矩形。这是代码:

svg.graph._wrapper.rect(group, 0, 100, 40, 20,
                       {fill: 'ivory',
                        stroke: 'black',
                        strokeWidth : 2});

So I thought I could easily change the fill instead of using 'ivory', I changed it to 'theImageIwantToUse'. But it does not seem to work.

所以我想我可以轻松地更改填充而不是使用“象牙”,我将其更改为“theImageIwantToUse”。但它似乎不起作用。

采纳答案by toniedzwiedz

You can insert images in your svg by using the <image>element http://www.w3.org/TR/SVG/struct.html#ImageElement

您可以使用<image>元素http://www.w3.org/TR/SVG/struct.html#ImageElement在 svg 中插入图像

An appropriate function is available in the plugin you mentioned.

您提到的插件中提供了适当的功能。

svg.image(parent, x, y, width, height, ref, settings)  

( http://keith-wood.name/svg.html)

( http://keith-wood.name/svg.html)

I doubt it's possible to use stroke in an image so you'll have to draw a rectangle with no fill after drawing the image to get the exact result you want.

我怀疑是否可以在图像中使用笔触,因此您必须在绘制图像后绘制一个没有填充的矩形才能获得所需的确切结果。

回答by Sirko

You can't insert an external image directly as the background to SVG objects.

您不能直接插入外部图像作为 SVG 对象的背景。

Instead, you first have to create a patttern like this

相反,您首先必须创建这样的模式

var ptn = svg.pattern(defs, "imgPattern", 0, 0, 100, 100, 0, 0, 10, 10, 
                      {patternUnits: "userSpaceOnUse"});
svg.image( ptn, 100, 50, 200, 200, "./theImageIwantToUse.png");

and use this pattern then via the url()function in the fill attribute

然后通过url()填充属性中的函数使用此模式

svg.graph._wrapper.rect(group, 0, 100, 40, 20,
                       {fill: 'url(#imgPattern)',
                        stroke: 'black',
                        strokeWidth : 2});