Argent Argent - 12 days ago 5
CSS Question

D3 setting stroke-dasharray through CSS

In D3 v4 I find that specifying stroke-dasharray as an attribute works as expected. On the other hand, specifying it through a style does not. Please see the code listing at the end of this note.

According to the Mozilla Foundation (https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes):

"Using CSS

In addition to setting attributes on objects, you can also use CSS to style fills and strokes. Not all attributes can be set via CSS. Attributes that deal with painting and filling are usually available, so fill, stroke, stroke-dasharray, etc... can all be set this way..."

So there is one of three possibilities:

1) I am not implementing the style properly in the sample code provided below.

2) D3 is not implementing the style properly.

3) The Mozilla Foundation is wrong about being able to set stroke-dasharray through CSS.

Which is it?

Code:

<!DOCTYPE html>
<html>
<head>
<script src='https://d3js.org/d3.v4.min.js'></script>
<style>
.dashed {
stroke-dasharray: '5,3';
}
</style>
</head>
<body>
<svg height=200 width=500></svg>
</body>
<script>
var svg = d3.select('svg');
svg.append('line')
.attr('x1', 0)
.attr('x2', 500)
.attr('y1', 25)
.attr('y2', 25)
.style('stroke', 'blue')
.style('stroke-width', '2px')
.style('stroke-dasharray', '5,3');
svg.append('line')
.attr('x1', 0)
.attr('x2', 500)
.attr('y1', 75)
.attr('y2', 75)
.style('stroke', 'blue')
.style('stroke-width', '2px')
.attr('class', 'dashed');
</script>
</html>

Answer

You are using a string in the CSS, which is an invalid property value. Instead of that, it should be a number:

.dashed {
    stroke-dasharray: 5,3;
}

Check it:

<html>
    <head>
        <script src='https://d3js.org/d3.v4.min.js'></script>
        <style>
            .dashed {
                stroke-dasharray: 5,3;
            }
        </style>
    </head>
    <body>
        <svg height=200 width=500></svg>
    </body>
    <script>
        var svg = d3.select('svg');
        svg.append('line')
            .attr('x1', 0)
            .attr('x2', 500)
            .attr('y1', 25)
            .attr('y2', 25)
            .style('stroke', 'blue')
            .style('stroke-width', '2px')
            .style('stroke-dasharray', '5,3');
        svg.append('line')
            .attr('x1', 0)
            .attr('x2', 500)
            .attr('y1', 75)
            .attr('y2', 75)
            .style('stroke', 'blue')
            .style('stroke-width', '2px')
            .attr('class', 'dashed');
    </script>
</html>

Thus, the correct answer is number 1:

1) I am not implementing the style properly in the sample code provided below.

Comments