更改方向后,SVG的viewBox无法正确显示

时间:2019-05-24 19:09:21

标签: javascript svg

我使用下面的代码通过SVG显示一些图形。以纵向或横向方式加载页面后,一切正常。但是当方向改变时,viewBox无法正确显示。例如,当以纵向模式加载页面并将方向更改为横向时,它会切一些圆并缩放viewBox,这是不正确的。我做错了什么?

viewPort.setAttribute("width", screen.width);
viewPort.setAttribute("height", screen.height);
viewPort.setAttribute("viewBox","0 0 "+(screen.width)+" "+(screen.height));

document.getElementById("header").style.width = screen.width;

document.getElementById("div1").style.width = window.innerWidth;
document.getElementById("div1").style.height = window.innerHeight;
document.getElementById("div1").style.minWidth = window.innerWidth;
document.getElementById("div1").style.maxWidth = window.innerWidth;
document.getElementById("div1").style.minHeight = window.innerHeight;
document.getElementById("div1").style.maxHeight = window.innerHeight;

document.getElementById("div2").style.width = screen.width;
document.getElementById("div2").style.height = screen.height;
document.getElementById("div2").style.minWidth = screen.width;
document.getElementById("div2").style.maxWidth = screen.width;
document.getElementById("div2").style.minHeight = screen.height;
document.getElementById("div2").style.maxHeight = screen.height;

function drawCircle(x) {
  var c = document.createElementNS("http://www.w3.org/2000/svg", 'circle');
  c.setAttribute('cx', x);
  c.setAttribute('cy', 50);
  c.setAttribute('r', 20);
  circle.appendChild(c);
}
var x = 50;
for (var i = 0; i < 10; i++) {
  drawCircle(x);
  x = x + 50;
}
body {
            margin: 0;
            overflow: hidden;
          }
          #header {
            width: 100%;
            height: 150px;
            background-color: blue;
          }
          #div1 {
            position: relative;
            overflow: auto;
            background-color: red;
            width: 100%;
            height: 0;
            left: 0; right: 0;
            top: 0; bottom: 0;
            min-width: 0;
            min-height: 0;
            max-width: 0;
            max-height: 0;
          }
          #div2 {
            position: relative;
            overflow: hidden;
            background-color: #ffffff;
            width: 100%;
            height: 0;
            left: 0; right: 0;
            top: 0; bottom: 0;
            min-width: 0;
            min-height: 0;
            max-width: 0;
            max-height: 0;
          }
<html>
      <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
      </head>
      <body>
        <div id="header">
        <div id="div1">
          <div id="div2">
            <svg id="viewPort" width="100%" height="100%" viewBox="0 0 0 0" preserveAspectRatio="none">
              <svg id="circle"></svg>
            </svg>
          </div>
        </div>
      </body>
    </html>

0 个答案:

没有答案