how to handle SVG pixel snapping
Asked Answered
F

2

6

I am trying to render two svg lines using path element. The first line has 1px width and it is sharp The second line has 2px width and it is blurred
The stroke-width is the same for both. How to fix this

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
 <path style="stroke-width:1;stroke:red;opacity:1;" d="M  300.5  250 L  300.5 300 "></path>
 <path style=" stroke-width:1;stroke:red;opacity:1;" d="M  350    250 L  350  300  "></path> 
</svg>
Farmann answered 24/10, 2013 at 6:23 Comment(0)
K
16

Mainly it's the 0.5 offset that makes the line sharp. By default, integer coordinates map to the intersections of the pixel squares. So a width-1 horizontal/vertical line is centered on the boundary between pixel rows and extends half way into the pixels on either side.

So to fix the second line either add 0.5 to the co-ordinates or use the style shape-rendering: crispEdges. Note that crispEdges prevents antialiasing so horizonal/vertical lines are crisp but angled lines look blocky.

Also stroke-width=1 is not valid CSS syntax. The first example stroke-width: 1 has it right.

Kirkwall answered 24/10, 2013 at 9:44 Comment(1)
Thanks a lot . I corrected the css syntax. It was added by mistake. Your solution worked for me . In case I have these lines tilted at some angle , after using the crispEdges , they do not look smooth they look like there are some steps on the lines. DO you any solution ? I need lines that are smooth and sharp even when rotated or tilted . Can you answer even this query of mine #17203852Farmann
B
-1

Just Try to move the SVG element.

svg {
  padding: .5px;
}
Bounden answered 30/5, 2020 at 9:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.