两个svg水平相连

Two svgs next to each other horizontally

本文关键字:水平 svg 两个      更新时间:2023-09-26

是否可能有多个svg水平相邻?我知道当你在D3中添加一个SVG时,它会添加到前面的SVG下面。但是现在我的前一个SVG位于页面的一半,我想将这个SVG从前一个SVG的下方转换到前一个SVG的右侧。我尝试在第二个svg上使用transform->translate属性,但它不起作用:

var secondSVG= d3.select("#div1").append("svg").attr("width",960).attr("transform"),"translate(500, -500)");

在Chrome 24, IE10和FF17中,这个jsFiddle工作如预期。关键似乎是设置widthheight样式表属性。

HTML:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="190" id="svg1">
  <polygon points="100,10 40,180 190,60 10,60 160,180"
  style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;">
</svg>
  <svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="190" id="svg2">
  <polygon points="100,10 40,180 190,60 10,60 160,180"
  style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;">
</svg>
CSS:

svg
{
  width: 190px;
  height: 190px;
}

之前我也想做类似的事情,但我最终决定使用一个svg元素和两个内部g元素,其中一个元素向右转换。你可以在这里看到最终的成品。

总体思路:将每个SVG包装在div元素中,该元素显示为inline-block。我个人喜欢下面的方法。

  • 设置svg的宽度和高度为100%。
  • "内部影响":用viewBox属性指定绘图区域的大小(svg中元素的单位,如圆,与之相关);这通常与preserveAspectRatio属性一起使用。
    https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox
    https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAspectRatio
  • "外部影响":集装箱将适应其集装箱的大小。样式(宽度和/或高度)根据你的愿望。当然你需要足够的水平空间。

最小的例子:

<div style="display: inline-block; width: 42%">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="-80 -45 160 90" preserveAspectRatio="xMinYMin meet">
<circle cx="0" cy="0" r="39">
</svg>
</div>
<!-- Just a copy from above. Right of (not below) the previous SVG. -->
<div style="display: inline-block; width: 42%">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="-80 -45 160 90" preserveAspectRatio="xMinYMin meet">
<circle cx="0" cy="0" r="39">
</svg>
</div>