Path intersection causes parts of them to disappear [D3 Path Generation]

Viewed 53

I've been trying to generate two paths on an SVG but it appears that one of the paths slightly disappears. I was wondering what's causing this issue. I've tried using different path drawing formula with no luck. The code is very simple as seen below:

     import * as d3 from "d3";

     let canvas =  d3.select('#canvas');
        let svg = canvas.append('svg')
        .attr('width',1820)
        .attr('height', 790)
        .style('background-color', 'black')

        var pathInfo = [
            {
              p: 'P',
              data:  [[0, 40], [50, 30], [100, 50], [200, 60], [300, 90]]
            },
            {
              p:'p2',
              data:  [[0, 40], [50, 30], [100, 50], [200, 60], [350, 90]]
            }
        ]
        const curve = d3.line().curve(d3.curveNatural);
        svg.selectAll('path')
        .data(pathInfo)
        .enter()
        .append('path')
        .attr('d', (d)=> curve(d.data)).attr('stroke', 'white')

enter image description here

1 Answers

If you set the fill property of your path to something like orange and reduce the opacity, the reason for the behavior you are seeing should become more apparent:

enter image description here

The default fill color for an SVG path is black - and a path is filled by default regardless of whether it's a closed path. The orange area above is black in your example. So the result you are seeing is due to the second path's fill covering the first path's stroke over most of its length. Hence, only part of the stroke is visible. The back background obfuscates the issue, but the solution is to set your fill to none:

let canvas =  d3.select('body');
        let svg = canvas.append('svg')
        .attr('width',1820)
        .attr('height', 790)
        .style('background-color', 'black')

        var pathInfo = [
            {
              p: 'P',
              data:  [[0, 40], [50, 30], [100, 50], [200, 60], [300, 90]]
            },
            {
              p:'p2',
              data:  [[0, 40], [50, 30], [100, 50], [200, 60], [350, 90]]
            }
        ]
        const curve = d3.line().curve(d3.curveNatural);
        svg.selectAll('path')
        .data(pathInfo)
        .enter()
        .append('path')
        .attr('d', (d)=> curve(d.data)).attr('stroke', 'white').attr("fill","none");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Related