I’m using the D3 javascript library to dynamically change line thicknesses. What I want to achieve is a line that increase in thickness, and decreases in thickness, repeatedly constantly. To draw a line, I used the following code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
</head>
<body>
<div id="D3line"></div>
<script type="text/javascript">
var lineSVG = d3.select("#D3line")
.append("svg:svg")
.attr("width", 500)
.attr("height", 200);
var myLine = lineSVG.append("svg:line")
.attr("x1", 60)
.attr("y1", 60)
.attr("x2", 450)
.attr("y2", 150)
.style("stroke", "rgb(6,120,155)")
.style("stroke-opacity", 2);
</script>
</body>
</html>
Then, to change the line stroke thickness, I used the following code:
var lines = lineSVG.selectAll("line") // select all lines
function makeLinesThick()
{
lines.transition().duration(500)
.style("stroke-width", "5")
.each("end", makeLinesThin);
}
function makeLinesThin(){
lines.transition().duration(500)
.style("stroke-width", "2")
.each("end", makeLinesThick);
}
// call function to change lines
makeLinesThick()
However, I end up with this not running properly and getting an ‘Unresponsive script’ message in my browser. I’m not sure if I am structuring the callbacks properly in this case.
Edit: I changed my incorrect callback handling by removing the () in the .each() line.
The problem is that
.each("end", ...)is called for every element that you’re selecting. That is,makeLinesThinis called once for each line inmakeLinesThick. This is what causes your browser to hang.There are several ways you could make it work. You could change your code to do the transitions for each line individually (see the documentation for
transition.each()) or you could schedule the transitions on all lines separately usingsettimeout(). Note in particular the documentation fortransition.transition()— you can schedule another transition before the current one is complete.You might also want to have a look at
d3.timer(), example here.