How to remove blank space around SVG

后端 未结 2 804
你的背包
你的背包 2021-02-14 07:02

I have an SVG showing on a simple web page, but once I resize the image beyond a certain size (height: ~65vh) the SVG has an invisible space around it that makes the page massiv

2条回答
  •  一生所求
    2021-02-14 07:42

    I made this codepen that might help others who don't want to deal with drawing tools:

    https://codepen.io/Steve6886/pen/abzzdOG

    EDIT: Here’s a more up-to-date version of my previous codepen solution: https://svgcrop.com

    // USER: Set either a width OR height (will scale evenly)
    const WIDTH = 100;
    const HEIGHT = null;
    
    // Grab the SVG and remove any existing viewBox
    const svg = document.querySelector('svg');
    svg.removeAttribute('viewBox');
    
    // Set default coordinates
    const coords = {
      top: Infinity,
      left: Infinity,
      bottom: -Infinity,
      right: -Infinity
    }; 
    
    // Filter SVG to visible elements
    filterize = newSvg => {
      const newest = [...newSvg.children].filter(x => x.tagName !== 'defs' && x.tagName !== 'style' && x.tagName !== 'title' && x.tagName !== 'desc');
      if ((newest.length === 1 && newest.childElementCount > 0) || newest[0].tagName === 'g') {
        return filterize(newest[0]);  
      }  
    
      return newest.filter(x => (x.getBoundingClientRect().top !== 0 && x.getBoundingClientRect().left !== 0 && x.getBoundingClientRect().bottom !== 0 && x.getBoundingClientRect().right !== 0));
      
    } 
    
    // Get coordinates of SVG elements
    filterize(svg).forEach(x => {
      const {top, left, bottom, right} = x.getBoundingClientRect();
      if (top < coords.top) {
        coords.top = x.getBoundingClientRect().top;
      }
      if (left < coords.left) {
        coords.left = x.getBoundingClientRect().left;
      }
      if (right > coords.right) {
        coords.right = x.getBoundingClientRect().right;
      }
      if (bottom > coords.bottom) {
        coords.bottom = x.getBoundingClientRect().bottom;
      }
    }); 
    
    // Set viewBox based on coordinates
    svg.setAttribute('viewBox', `${coords.left.toFixed(2)} ${coords.top.toFixed(2)} ${(coords.right - coords.left).toFixed(2)} ${(coords.bottom - coords.top).toFixed(2)}`);
    
    // Set given width OR height
    WIDTH && svg.setAttribute('width', WIDTH);
    HEIGHT && svg.setAttribute('height', HEIGHT);  
    
    // Add textarea with new SVG code to copy
    const textarea = document.createElement('textarea');
    textarea.style = `display:block;margin-top:2rem;width:100%;padding:0;min-height:calc(100vh - ${getComputedStyle(svg).height} - 2rem);`;
    textarea.innerHTML = svg.outerHTML;
    document.body.appendChild(textarea); 
    

提交回复
热议问题