SVG:在子元素内部绘制

SVG: drawing inside a child element

本文关键字:内部 绘制 元素 SVG      更新时间:2023-09-26

我正在使用d3.js库,需要在另一个子svg元素中绘制一些svg元素。例如,我在svg中有一个容器元素,它是一个"rect"。我也想在"矩形"里面画一些线。但我在看这些台词时遇到了问题。

如果我将这些行添加到主svg容器中,它就可以正常工作。但是当我将这些线添加到"rect"中时,这些线是不可见的。我想,协调是问题所在。

那么,有人能告诉我,在子元素内部绘制时应该如何计算坐标吗?它是否会自动偏移其父坐标?或者"rect"会有自己的坐标系?

<line>不会在<rect>内部呈现。

如果你看https://www.w3.org/TR/SVG/shapes.html#RectElement,仅允许动画和描述性元素作为<rect> 的内容

您可能需要重新构造代码,以使用g元素作为容器元素,将相关的图形元素(如<rect><line>)分组在一起。

如果需要定位分组元素,可以使用变换。

<svg width="1000" height="500">
  <g transform="translate(10,30)">
    <rect x="0" y="0" width="100" height="50" style="fill:black;"></rect>
    <line x1="20" y1="0" x2="20" y2="20" stroke="white" stroke-width="2"></line>
    <line x1="40" y1="0" x2="40" y2="20" stroke="white" stroke-width="2"></line>
    <line x1="60" y1="0" x2="60" y2="20" stroke="white" stroke-width="2"></line>
    <line x1="80" y1="0" x2="80" y2="20" stroke="white" stroke-width="2"></line>
  </g>
</svg>

https://jsfiddle.net/ksav/wq6mvv9v/