sjsc sjsc - 3 months ago 24
Javascript Question

SVG rectangle's stroke widths are cut off on top/left. How do I fix this?

My SVG's strokes are somehow cut off when I have a large stroke width for my rectangle. I have the following code:

<svg width="500px" height="300px">
<rect width="352" height="128" stroke="#333" stroke-width="16" fill-opacity="0"/>
</svg>


Here's the jsfiddle: https://jsfiddle.net/7ej6fzbg/3/

As you can see from the jsfiddle, the stroke widths are cut slightly for the top and left sides of the rectangle. How do I fix this such that the stroke widths are 16 pixels across the entire rectangle?

I believe I can change the x and y positions of the rectangle, but I believe that wouldn't be very robust if I wanted to change the stroke width later on. Any ideas?

Answer

Since the rect strokes are centered on the boundary of the rectangle, either use half the stroke width every time (8 in this case) for X and Y:

<svg width="500px" height="300px">
    <rect x="8" y="8" width="352" height="128" stroke="#333" stroke-width="16" fill-opacity="0"/>
</svg>

or offset the viewbox of the SVG by half the stroke width:

<svg width="500px" height="300px" viewbox="-8 -8 492 292">
    <rect width="352" height="128" stroke="#333" stroke-width="16" fill-opacity="0"/>
</svg>