Find svg viewbox that trim whitespace around

前端 未结 1 1042
别跟我提以往
别跟我提以往 2020-11-28 13:47

Assuming I have an svg that draws some paths, what tools should I use to find a viewbox that perfectly fits those paths so that all redundant space around is trimmed?

相关标签:
1条回答
  • 2020-11-28 14:28

    You can simply set your svg's viewBox to its Bounding Box.

    function setViewbox(svg) {
      var bB = svg.getBBox();
      svg.setAttribute('viewBox', bB.x + ',' + bB.y + ',' + bB.width + ',' + bB.height);
      }
    
    document.querySelector('button').addEventListener('click', function() {
      setViewbox(document.querySelector('svg'));
      });
    svg {  border: 1px solid }
    <svg version="1.1" id="svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 500 300" enable-background="new 0 0 500 300" xml:space="preserve" width="250" height="150">
      <path fill="none" stroke="#B2E230" d="M413.7,276.5c0,0,67-37,116,0c-24.1-33,16.4-53,0-34s-100-2-75-38" transform="translate(-75,-75)" />
    </svg>
    <button>setViewbox</button>

    Note: It will also take into account the non-visible anchors of your pathes.

    0 讨论(0)
提交回复
热议问题