Why is there whitespace / “overlap” between rect e

2019-07-23 18:19发布

I'm using d3.js to generate some rects which are directly above one another, in this fashion:

var greenRed = d3.select(".green-red").append("svg")
    .attr("height", 120);
greenRed.append("rect")
    .attr("fill", "green")
    .attr("x", 0)
    .attr("y", 0)
    .attr("height", 50)
    .attr("width", 300);
greenRed.append("rect")
    .attr("fill", "red")
    .attr("x", 0)
    .attr("y", 50)
    .attr("height", 50)
    .attr("width", 300);

I've noticed that depending on which colours are stacked on top of one another, there is either a very thin whitespace present between the rectangles, or a sort of "overlap" of the two colours.

You can see what I mean in this fiddle: http://jsfiddle.net/ysim/PrC7X/

You can see that for .green-green and .green-grey there's no issue (to the naked eye, anyway); but for .green-blue and .red-blue, there is an overlap, and for .green-red, there is an extra whitespace.

I've tried adding .attr("stroke-rendering", "crispEdges") (suggested here) and .attr("stroke", "none") to the rect elements, as well as wrapping both the rect elements in a g element within the svg and adding .attr("stroke-rendering", "crispEdges") to that (suggested here), but neither of those solutions work.

What's causing this extra whitespace/overlap, and how do I go about fixing it so that the colours are neatly aligned, like in the first two cases?

2条回答
做自己的国王
2楼-- · 2019-07-23 19:03

That's antialiasing. Add style="shape-rendering: crispEdges" to the <div> elements and it will go away. You could add it to the shapes themselves instead if you want either as an attribute or a style.

The other thing to do is to add 0.5 to the y co-ordinates of your shapes There's more information about why that works here

查看更多
Evening l夕情丶
3楼-- · 2019-07-23 19:03

try setting the stroke-width property to 0

查看更多
登录 后发表回答