ASA
ASA

Reputation: 1971

How to draw single Pixel lines with d3.js / SVG

I want to draw vertical and horizontal lines with exactly one pixel width and an exactly defined color. Whatever I am trying I can not make one solution work in Firefox, Chrome and Internet Explorer at once correctly.

Say I want to draw a black full horizontal line in the second pixel line, in d3.js you'd think this is the solution:

.append("line")
.attr("x1", 0)
.attr("y1", 1.5)
.attr("x2", 100)
.attr("y2", 1.5)
.attr("stroke-width", 0.5)
.attr("stroke", "black");

Mathematically it should do exactly what I want, no? Nope, it doesn't. Firefox doesn't display it, IE and Chrome make it grey/transparent. Not using a +0.5 offset for the y value doesn't help, anything with stroke-width 1 doesn't help either. Each browser does have one exact solution, but there is none that is right with all three. If that isn't enough you can even add the shape-rendering attribute to the equation, which too doesn't help. Is there any one size fits all solution for those three browser or do I seriously have to modify the line creation depending on browser?

Upvotes: 2

Views: 1544

Answers (1)

meetamit
meetamit

Reputation: 25157

It's due to anti aliasing, and it's known that some browsers apply it to lines that run along the .5 of the pixel and others do it on the whole pixel.

svg elements have a css prop to override this.

shape-rendering: crispEdges

https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/shape-rendering

Upvotes: 4

Related Questions