偏移(使用变换)svg 元素相对于它自己的大小
offset (using transform) svg element relative to its own size
我想使用百分比转换相对于其自身大小偏移 SVG 元素,这与使用 transform: translate(100%,0)
偏移 div 的工作方式非常相似:
此代码:
<div style={{ overflow: 'visible', position: 'relative' }}>
{/* rect */}
<div style={{ height: 20, width: 20, background: 'black', position: 'absolute' }} />
{/* circle */}
<div
style={{
height: 20,
width: 20,
background: 'purple',
borderRadius: '50%',
position: 'absolute',
transform: 'translate(100%,0)',
}}
/>
</div>
看起来像这样
很好,圆偏移是相对于它自己的大小
而这种情况:
<svg overflow={'visible'}>
<rect width={20} height={20} />
<circle cx={10} cy={10} r="10" fill="purple" style={{ transform: 'translate(100%,0px)' }} />
</svg>
将导致渲染:
它基本上是相对于 svg canvas(我从未明确设置)的大小进行偏移:
为什么 transform: 'translate(100%,0)'
在 div html 元素中相对于自身起作用,但在 SVG 元素中相对于父元素起作用?
已经尝试过:
- 包装
g
个元素,或 svg
个类似于本网站其他答案的元素。
想避免:
- 我可以通过使用 .getbBox() 函数并手动计算尺寸并将其保存到状态然后按像素偏移来解决这个问题,但我真的想避免它并正在寻找更简单的解决方案。
演示
https://codesandbox.io/s/svg-vs-div-transform-translate-o2ii7
您应该将变换框设置为填充框。对于 React,您使用驼峰式大小写,因此它看起来像这样:
style={{ transform: "translate(100%,0px)", transformBox: "fill-box" }}
我想使用百分比转换相对于其自身大小偏移 SVG 元素,这与使用 transform: translate(100%,0)
偏移 div 的工作方式非常相似:
此代码:
<div style={{ overflow: 'visible', position: 'relative' }}>
{/* rect */}
<div style={{ height: 20, width: 20, background: 'black', position: 'absolute' }} />
{/* circle */}
<div
style={{
height: 20,
width: 20,
background: 'purple',
borderRadius: '50%',
position: 'absolute',
transform: 'translate(100%,0)',
}}
/>
</div>
看起来像这样
而这种情况:
<svg overflow={'visible'}>
<rect width={20} height={20} />
<circle cx={10} cy={10} r="10" fill="purple" style={{ transform: 'translate(100%,0px)' }} />
</svg>
将导致渲染:
它基本上是相对于 svg canvas(我从未明确设置)的大小进行偏移:
为什么 transform: 'translate(100%,0)'
在 div html 元素中相对于自身起作用,但在 SVG 元素中相对于父元素起作用?
已经尝试过:
- 包装
g
个元素,或svg
个类似于本网站其他答案的元素。
想避免:
- 我可以通过使用 .getbBox() 函数并手动计算尺寸并将其保存到状态然后按像素偏移来解决这个问题,但我真的想避免它并正在寻找更简单的解决方案。
演示
https://codesandbox.io/s/svg-vs-div-transform-translate-o2ii7
您应该将变换框设置为填充框。对于 React,您使用驼峰式大小写,因此它看起来像这样:
style={{ transform: "translate(100%,0px)", transformBox: "fill-box" }}