如果你正确地编写了 SVG,那么使用哪个
<g>
进行翻译并不重要:
svg {
border: 1px solid black;
}
<svg width="300" height="300" fill="#FFDDDD" viewBox="0 0 100 100">
<g transform="translate(100,100)">
<g transform="translate(0,0)">
<circle cx="-50" cy="-50" r="10" fill="black" />
</g>
</g>
</svg>
<svg width="300" height="300" fill="#FFDDDD" viewBox="0 0 100 100">
<g transform="translate(0,0)">
<g transform="translate(100,100)">
<circle cx="-50" cy="-50" r="10" fill="black" />
</g>
</g>
</svg>
但是,这确实需要编写正确的 SVG:一个
<svg>
根,带有 viewBox
属性,以便浏览器知道它实际渲染的内容,并且没有嵌套 <svg>
元素:
// you don't need a `<g>` if you're transforming a single element.
// the "transform" attribute can be used on *any* SVG element.
const Piece = ({ tx:0, ty:0 }) => (
<circle cx="-50" cy="-50" r="10" fill="black" transform="translate({tx},{ty})"/>
);
// But you need viewBox, otherwise your SVG cannot be rendered correctly.
// However: here, too, you don't need <g>
const SVG = ({ tx:0, ty:0 }) => (
<svg width="100" height="100" fill="#FFDDDD" viewBox="0 0 100 100">
<Piece tx={tx} ty={ty}/>
</svg>
);
const root = ReactDOM.createRoot(document.getElementById("app"));
root.render(<SVG tx={100} ty={100}/>);