How use an SVG image as a background?

2019-06-15 23:48发布

I must be doing something wrong. The image was exported from illustrator as an SVG and (I'm not sure whether this is relevant or not) it does have some pixel data in it. Here's my JSFiddle example.

Note that going directly to the image, it shows up just fine: http://ykcreations.com/tv.svg


Edit: This does not work in Chrome or Safari but DOES in Firefox. Webkit issue?

标签: css html5 svg
4条回答
Summer. ? 凉城
2楼-- · 2019-06-16 00:16

Another possible cause is serving the SVG with the wrong MIME type. Setting it to 'image/svg+xml' may fix the issue.

In Rails, this can be done by adding the following to config/intializers/mime_types.rb:

Mime::Type.register 'image/svg+xml', :svg

查看更多
Root(大扎)
3楼-- · 2019-06-16 00:21

There is a problem with your source SVG. See this updated Fiddle pointing to a different SVG file that works correctly: http://jsfiddle.net/wdW2K/2/

.tv {
  background: url("http://phrogz.net/svg/800x800.svg");
  width: 400px; height: 400px;
}​

Edit: Specifically, the problem appears to be that WebKit does not support <image> in an SVG used as a background. Modifying your file minimally to change the <image> to reference a local (non-data-uri) file, and adding a <circle/>, I was able to see both the image and circle when viewing the SVG directly in Chrome, but when used as a background image only the circle was visible.

This bug smells relevant.

查看更多
疯言疯语
4楼-- · 2019-06-16 00:26

I had a simmilar problem with rendering svg as background image in Chrome, but everything was fine in Firefox. I found out that there was a syntax error inside my svg files exported from Adobe:

wrong xlink attribute:

xlink:href="data:img/png;base64

correct xlink attribute:

xlink:href="data:image/png;base64

Article bellow:

Link to article from css-trick that helped me

查看更多
我想做一个坏孩纸
5楼-- · 2019-06-16 00:31

It has to do with your image, try plugging the following into your CSS:

.tv
{
    background-image: url("http://croczilla.com/bits_and_pieces/svg/samples/butterfly/butterfly.svg");
    width: 400px;
    height: 400px;
}​

Perhaps your SVG is actually an SVGZ? SVGZ files are the compressed versions of SVG files. Usually you have to configure your server to handle that, but FF may just be able to deal with the compressed versions.

EDIT See Phrogz's answer below (possibly above by the time you read this); it covers this and gives a better explanation.

查看更多
登录 后发表回答