0

I'm using inline svgs. I have a svg circle and fill it with a pattern. The image inside needs to 100% of container size. This works until the parent element gets resized.

When the parent element(div) gets resized via js the pattern wont reflect 100% width and height anymore. This works in Firefox though.

To me it seems like the css doesnt get updated. If I change the value to 99% manually Chrome updates the size on both dimensions.

This is the structure of my svg:

<div style="height:150px; width:150px;">
  <svg style="height:100%; width:100%;">
    <defs>
       <pattern id="image" x="0%" y="0%" width="100%" height="100%">
         <image x="0%" y="0%" width="58%" height="58%" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="image.jpg"></image>
       </pattern>
    </defs>
    <circle cx="50%" cy="50%" r="29%" fill="url(#image)">
    </circle>

    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#other"></use>
  </svg>
<div>

I had found similar questions, but without help:

Image inside svg pattern is blurried after zoom in Chrome (there the image gets blurry)

SVG <pattern> won't load when generated by Javascript (the question got closed without a good answer)

Tigerware
  • 3,196
  • 2
  • 23
  • 39

1 Answers1

0

You need to add viewBox property in svg, please refer the following link: https://css-tricks.com/scale-svg/

Updated Code -

function inc(){
var parent = document.getElementById('parent');
parent.style.width = '350px';
parent.style.height = '350px';

}
<div id='parent' style="height:150px; width:150px;">
  <svg style="height:100%; width:100%;" viewBox="0 0 50 50">
    <defs>
       <pattern id="image" x="0%" y="0%" width="100%" height="100%">
         <image x="0%" y="0%" width="58%" height="58%" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="image.jpg"></image>
       </pattern>
    </defs>
    <circle cx="50%" cy="50%" r="29%" fill="url(#image)">
    </circle>

    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#other"></use>
  </svg>
<div>

<a href="#" onclick="inc()">Increase</a>
Ayush Sharma
  • 2,057
  • 15
  • 25
  • Does that work with 100%? I tried it, and it seemed to work, but the same problem occurs (the circle size, doesnt get updated). I guess I should set the viewBox to the same value as the div? (That way the circle should always be the right size and gets updated since the value changed.) Anything wrong with that approach? – Tigerware Jun 30 '17 at 14:19
  • @Blue As per my understanding we can not give % values for viewBox attribute, you can refer the below link to get more understanding on viewBox - http://tutorials.jenkov.com/svg/svg-viewport-view-box.html – Ayush Sharma Jul 03 '17 at 08:50