在页面的左侧或右侧显示SVG对象

Displaying SVG objects on either left or right side of page

本文关键字:显示 SVG 对象      更新时间:2023-09-26

我正在动态生成一些SVG。我想做的是将页面一分为二(无论大小),并能够在屏幕左侧插入一些对象,在屏幕右侧插入一些对象。我就是好像做不好。事实上,我已经尝试过很多不同的方法,这里列出的代码是我最近的尝试:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  width="100%" height="100%">
  <script type="text/ecmascript">
    var svgNS = "http://www.w3.org/2000/svg";
    var xlinkNS = "http://www.w3.org/1999/xlink";
   var i = 0;
  function makeBox() {
     i++;
      var newRect = document.createElementNS(svgNS,"rect");
     newRect.setAttributeNS(null,"width", 100); 
     newRect.setAttributeNS(null,"height", 100);
     newRect.setAttributeNS(null, "x", 10);
     newRect.setAttributeNS(null, "y", i * 100);
     newRect.setAttributeNS(null,"fill","blue");      

     if(i % 2 === 1) {
     document.getElementById("screenLeft").appendChild(newRect);
      } else {
     document.getElementById("screenRight").appendChild(newRect);
      }
  }

</script>
  <g id="firstGroup">
<text x="20" y="30" onclick="makeBox()" font-size="+13px">Click this text to Draw a Box.</text>
</g>
<svg id="screenLeft" viewBox="50% 100%">
</svg>
<svg id="screenRight" viewBox="50% 100%" x="50%">
</svg>  
</svg>

当然,我修改了一堆代码,使这篇文章更加简洁。它所做的是,当用户单击文本时,它在元素"screenLeft"或"screenRight"中绘制一个矩形,这取决于增量(i)是偶数还是奇数。

我现在设置viewBox的方式有点正常。如果我把铬窗口缩小到更小的尺寸,"左侧"answers"右侧"之间的间隙就会变小。然而,如果我让窗口最大化,屏幕区域太大了。我必须向右滚动才能看到"右侧"。它大约是我屏幕大小的两倍。

我还尝试了其他几种方法,包括分组。

所以,我想我的问题是,将屏幕一分为二的最佳方法是什么,这样我就可以在屏幕左侧和右侧生成一些对象,同时允许总屏幕大小不同?

<svg>元素一个具有固定宽度和特殊高度的viewBox。然后指定一个值为xMidYMid slicepreserveAspectRatio属性。

这将确保SVG视口的全宽始终覆盖viewBox,因此viewBox的一半将覆盖屏幕的一半。

<svg xmlns="http://www.w3.org/2000/svg"
     viewBox="-100 -1000 200 2000" preserveAspectRatio="xMidYMid slice">
  <style type="text/css"><![CDATA[
    rect { stroke:red }
    text { text-anchor:middle; font-size:8px }
  ]]></style>
  <rect x="-100" y="-1000" width="100" height="2000" fill="lightblue" />
  <rect x="0"    y="-1000" width="100" height="2000" fill="yellow"    />
  <text x="-50" y="0">Left Side</text>
  <text x="+50" y="0">Right Side</text>
</svg>

现场观看:http://phrogz.net/svg/half-width.svg

唯一的缺点(我不知道这对你是否重要)是调整浏览器窗口的大小会调整元素的大小。也许您希望无论浏览器有多大,元素在屏幕上的大小都保持不变?

这似乎达到了我认为你想要的效果,你唯一需要决定的就是你希望纵横比如何影响你的显示。。。我故意不调整右侧的纵横比,这样你就可以看到差异。

<svg  xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >
<svg width="50%" viewBox="0 0 100 100" preserveAspectRatio="none">
    <rect x="0" y="0" width="100%" height="100%" fill="red" opacity="0.5"/>
</svg>
<svg x="50%" width="50%"  viewBox="0 0 100 100" >
    <rect x="0" y="0" width="100%" height="100%" fill="blue" opacity="0.5"/>
    <rect x="80%" y="10%" width="10%" height="50%" fill="green"/>
    <rect x="10" y="10" width="70" height="40" fill="gray"/>
</svg>

相关文章: