【问题标题】:Two different views of the same svg drawing同一 svg 绘图的两个不同视图
【发布时间】:2016-10-05 06:26:21
【问题描述】:

我想使用 SVG 制作一个相当大的图表(我一直在 JavaScript 中使用 Snap.svg)。我想在一个元素中显示图表的可缩放部分,并在另一个元素中显示整个事物的较小版本,用户可以在其中导航。

一个策略是这样的:

制作两个相同的 SVG,除了它们有不同的viewBoxes,并且每次我更改其中一个 svg 元素时,对另一个副本进行相同的更改。 viewBox 属性使每个视图都显示图表的右侧部分。

这是一个好策略吗?对我来说似乎很脆弱和​​浪费。还有其他更聪明的方法吗?我真的要画两次吗?

希望“D'oh!”

【问题讨论】:

标签: javascript svg snap.svg viewbox


【解决方案1】:

是的,可以有一个主 SVG,然后自动更新同一图像的“缩略图”和/或“缩放”版本。

document.getElementById("but").addEventListener("click", function() {
  var svg = document.getElementById("mainsvg");
  var c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
  c.setAttribute("cx", 1000*Math.random());
  c.setAttribute("cy", 1000*Math.random());
  c.setAttribute("r", 50);
  c.setAttribute("fill", "red");
  svg.appendChild(c);
});
#main {
    width: 400px;
    height: 400px;
}

#thumb,
#zoom {
    display: inline-block;
    width: 80px;
    height: 80px;
}

svg {
  border: solid 1px grey;
}
<div id="main">
    <svg id="mainsvg" viewBox="0 0 1000 1000">
        <rect x="100" y="100" width="500" height="500" fill="green"
              transform="rotate(10,350,350)"/>
        <rect x="400" y="400" width="500" height="500" fill="orange"
              transform="rotate(-10,650,650)"/>
    </svg>
</div>


<div id="thumb">
    <svg xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1000 1000">
        <use xlink:href="#mainsvg" />
    </svg>
</div>


<div id="zoom">
    <svg xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1000 1000">
        <use xlink:href="#mainsvg" 
             x="-500" y="-1200"
             width="3000" height="3000" />
        <!-- control the zoom and position with x, y, width and height -->
    </svg>
</div>


<div>
  <button id="but">Click me</button>
</div>

【讨论】:

  • 巧妙!我以前从未使用过&lt;use&gt;;我会研究你的例子并尽快回到这个问题。
猜你喜欢
  • 2014-12-21
  • 2021-04-22
  • 2019-06-12
  • 1970-01-01
  • 1970-01-01
  • 2012-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多