D3 maintains line width when scaling

Next, two lines are created with a thickness of 8:

var a = [23,50]
for (b = 0; b < a.length; b++) {
var stripe = vis.selectAll("line.stripep")
.data(connections.filter(function(d,i) { return i == a[b];  }))
.enter().append("svg:line")
  .attr("class", "stripe")
  .attr("stroke", function(d) { return "#000000"; })
  .attr("stroke-linecap", 'round')
  .style("stroke-width",  function(d) { return 8; } )
  .attr("x1", function(d) { return x(d.station1.longitude); })
  .attr("y1", function(d) { return y(d.station1.latitude); })
  .attr("x2", function(d) { return x(d.station2.longitude); })
  .attr("y2", function(d) { return y(d.station2.latitude); })


} 

I have the following function to scale

function zoomed() {

vis.selectAll("line.route, line.stripe, line.stripep")
.attr("transform", "translate(" + zoom.translate() + ")scale(" + zoom.scale() + ")")
vis.selectAll("line.stripep")
.attr("stroke-width", 8 / (zoom.scale()))

}

However, the line thickness does not change, what is the problem.

I also tried:

vis.selectAll("line.stripep")
.style("stroke-width", 8 / (zoom.scale()))
+4
source share
2 answers

This piece of CSS stylesheets solves the problem perfectly:

.line {
    stroke-width: 2px; // desired stroke width (line height)
    vector-effect: non-scaling-stroke; // line height won't scale
}

No need for additional JS code.

+5
source

zoom.scale()Use insteadd3.event.scale();

Here is an example that I followed: http://jsfiddle.net/thatoneguy/aVhd8/565/1/

Here is the zoom function:

function zoomed() {
          container.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
          link.style("stroke-width", 8/d3.event.scale);
        }

In your case, it will be:

 vis.selectAll("line.stripep").style("stroke-width", 8/d3.event.scale);
+3
source

All Articles