javascriptcsssvg

equivalent in JS of the resize css applied to an SVG element


I recently discovered the CSS resize property:

div {
  resize   : both;
  overflow : auto;
  }

There is also a polyFill, but none of them won't work for a SVG element :/
Is it possible at least?


Solution

  • Starting from your code and @ChrisG's comment, you might do the following.

    When one clicks on svg, wrap this svg into a resizable div and set the svg width and height attributes to '100%' so the svg would get the wrapper's size.
    Then, when one resizes the div, the svg would be resized as well.
    When one clicks out of the div, set the svg width and height attributes explicitly and remove the div.

    See the snippet below:

    window.addEventListener('DOMContentLoaded', () => {
      document.addEventListener('click', (e) => {
        var r = document.getElementById('r');
        if (r && r != e.target) {
          var svg = r.querySelector('svg');
          svg.setAttribute('width', r.offsetWidth + 'px');
          svg.setAttribute('height', r.offsetHeight + 'px');
          r.replaceWith(svg);
        }
    
        var svg = e.target;
        while (!!svg && svg.nodeName != 'svg')
          svg = svg.parentElement;
        if (!svg) return;
    
        var r = document.createElement('div');
        r.id = 'r';
        r.style.width = svg.width.baseVal.valueAsString;
        r.style.height = svg.height.baseVal.valueAsString;
        svg.setAttribute('width', '100%');
        svg.setAttribute('height', '100%');
        svg.parentElement.insertBefore(r, svg);
        r.appendChild(svg.parentElement.removeChild(svg));
    
      });
    });
    svg {
      background: #cef
    }
    
    #r {
      display: inline-block;
      box-sizing: border-box;
      border: solid 1px;
      resize: both;
      overflow: hidden;
    }
    <svg width="100px" height="100px" viewBox="0 0 100 100">
      <circle stroke="navy" stroke-width="5" fill="pink" cx="50" cy="50" r="40"/>
    </svg>
    
    <svg width="100px" height="100px" viewBox="0 0 100 100">
      <circle stroke="green" stroke-width="5" fill="gold" cx="50" cy="50" r="40"/>
    </svg>