使SVG准确填满整个页面

使SVG准确填满整个页面

本文介绍了使SVG准确填满整个页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用纯Javascript开发一个简单的单页应用程序,并希望使用整页SVG作为图形基础.

I am making a simple single-page application in plain Javascript and want to use a full-page SVG as the graphics foundation.

我本以为放下

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

页面正文中的

可以解决问题.几乎可以用,但是效果不佳:

in the page body would do the trick. It almost works, but not quite:

  • 页面具有垂直滚动条(我不希望这是因为100%不应表示大于100%",因此没有任何内容可滚动到该滚动条.)
  • SVG左上角到页面大约20个像素(两个维度)
  • SVG的右侧被截断了-SVG和滚动条之间大约有10个像素列是空白的(我什至不希望也不期望).
  • the page has a vertical scrollbar (which I wouldn't expect because 100% should not mean "greater than 100%" and therefore there should be nothing to scroll to).
  • the SVG top-left corner is about 20 pixels into the page (in both dimensions)
  • the right side of the SVG is truncated -- about 10 pixel columns are blank between the SVG and the scrollbar (that I don't even want nor expect).

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

To show these problems clearly, I added Javascript code to draw a big bounding rectangle with an X in it after retrieving the SVG client coordinates.

<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默认值,或者类似的奇妙事物?

Any thoughts on what is crufting up the SVG bounds? Perhaps some kind of border defaults or CSS defaults or some wonderful thing like that?

推荐答案

您可能需要将CSS中的默认边距和填充归零,例如:

You might need to zero out the default margin and padding in CSS like:

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

这篇关于使SVG准确填满整个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 22:04