user3809938
user3809938

Reputation: 1304

D3 keep line width same when zooming

The following creates two lines with thickness 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 for zooming

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()))

Upvotes: 12

Views: 3384

Answers (2)

Jan Vorisek
Jan Vorisek

Reputation: 549

This piece of CSS styling perfectly solves the issue:

.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.

Upvotes: 23

thatOneGuy
thatOneGuy

Reputation: 10622

Instead of zoom.scale() use d3.event.scale();

Here is an example I have implemented : 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);

Upvotes: 3

Related Questions