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

柔情痞子 提交于 2019-12-01 14:33:49

问题


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

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.


回答1:


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

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 )

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.




回答2:


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

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

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


来源:https://stackoverflow.com/questions/10736946/how-to-set-a-svg-rect-elements-background-image

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!