为什么我必须更改此“rect”的“x”和“y”值才能使其位于其视口的左上角?

ton*_*120 5 html css svg

<svg width="200" height="200" style="border: solid blue 5px;">
  <rect x="0" y="0" height="50" width="100" stroke="purple" stroke-width="30px" fill="green"/>
</svg>
Run Code Online (Sandbox Code Playgroud)

需要什么才能使rect右侧靠在其容器的左上角?


解决方案 - 但不知道为什么

<svg width="200" height="200" style="border: solid blue 5px; overflow: visible">
  <rect x="15" y="15" height="50" width="100" stroke="purple" stroke-width="30px" fill="green"/>
</svg>
Run Code Online (Sandbox Code Playgroud)

Vic*_*kel 0

有3种可能:

  1. 根据笔划宽度计算矩形的 xy 偏移量,以补偿笔划宽度的偏移错位:offset-xoffset-ystroke-width / 2

<svg width="200" height="200" style="border: solid blue 5px;">
  <rect x="15" y="15" height="50" width="100" stroke="purple" stroke-width="30px" fill="green"/>
</svg>
Run Code Online (Sandbox Code Playgroud)

  1. 您可以使用 2 个矩形,而不是通过描边制作第二个颜色形状stroke-width="0px":将外部矩形的高度和宽度添加 30px,然后从内部矩形中减去 30px,这会得到与上面相同的结果

<svg width="200" height="200" style="border: solid blue 5px;">
  <rect x="0" y="0" height="80" width="130" stroke="purple" stroke-width="0px" fill="purple"/>
  <rect x="30" y="30" height="20" width="70" stroke="purple" stroke-width="0px" fill="green"/>
</svg>
Run Code Online (Sandbox Code Playgroud)

  1. 如果您不需要关心 svg 视口(外部边界框)的大小,您也可以获得相同的结果,将 svg 高度和宽度设置为内部矩形,并使用 of 补偿笔划padding宽度stroke-width/2

<svg width="100" height="50" style="border: solid blue 5px; padding:15px; background-color:purple;">
  <rect x="0" y="0" height="50" width="100" stroke="purple" stroke-width="30px" fill="green"/>
</svg>
Run Code Online (Sandbox Code Playgroud)

另请参见:StrokeWidthProperty

该属性指定当前对象上的描边宽度。
零值将导致不绘制任何笔划。