代码之家  ›  专栏  ›  技术社区  ›  personal_cloud

使SVG精确填充整个页面

  •  1
  • personal_cloud  · 技术社区  · 6 年前

    我在简单的JavaScript中编写一个简单的单页应用程序,并希望使用一个完整的页面SVG作为图形基础。

    我本来会想到

    <svg id="svg" width="100%" height="100%"></svg>
    

    在页面中,正文会起作用。它几乎可以工作,但不完全可以:

    • 页面有一个垂直滚动条(我不希望这样,因为 100% 不应表示“大于100%”,因此不应滚动到任何内容)。
    • SVG左上角进入页面大约20像素(在两个维度中)
    • SVG的右侧被截断——在SVG和滚动条之间大约有10个像素的列是空白的(我甚至不想也不期望)。

    为了清楚地显示这些问题,在检索SVG客户机坐标后,我添加了javascript代码来绘制一个带有x的大边界矩形。

    <html><body>
    
    <svg id="svg" width="100%" height="100%"></svg>
    
    <script>
    
    let svg = document.getElementById("svg");
    
    function line(x1, y1, x2, y2)
    {
        let e = document.createElementNS(svg.namespaceURI, 'line');
        e.setAttribute('x1', x1);
        e.setAttribute('y1', y1);
        e.setAttribute('x2', x2);
        e.setAttribute('y2', y2);
        e.setAttribute('style', 'stroke:#000');
        svg.appendChild(e);
    }
    
    function frame_rect(r)
    {
        let e = document.createElementNS(svg.namespaceURI, 'rect');
        e.setAttribute('x', r.x);
        e.setAttribute('y', r.y);
        e.setAttribute('width', r.width);
        e.setAttribute('height', r.height);
        e.setAttribute('style', 'stroke:#000;fill:none');
        svg.appendChild(e);
    }
    
    onresize = function()
    {
        svg.innerHTML = ''; // remove all elements from the SVG
        let r = svg.getBoundingClientRect();
        line(r.x,r.y,r.x+r.width,r.y+r.height);
        line(r.x,r.y+r.height,r.x+r.width,r.y);
        frame_rect(r);
    }
    onresize()
    
    </script></body></html>

    有没有想过什么是提高SVG的界限?也许是某种边界默认值,或者CSS默认值,或者类似的奇妙的东西?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Anthony    6 年前

    您可能需要在CSS中消除默认的边距和填充,例如:

    html, body, * { 
         margin: 0; 
         padding: 0; 
    }