Reputation: 15286
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.
Upvotes: 3
Views: 6527
Reputation: 46
var mutateLine =
function(line, t, width, altWidth) {
d3.select(line).transition().duration(t).style("stroke-width", width)
.each("end", function() {
if ( mutateLine ) mutateLine(line, t, altWidth, width);
});
}
// assumes lines is obtained from d3.selectAll()
var mutateLines =
function(lines, t, width, altWidth) {
if ( !mutateLine)
return;
lines[0].forEach(function(line) {
mutateLine(line, t, width, altWidth);
}
};
// start mutating
mutateLines(lines, 500, 5, 2);
// stop mutating
mutateLine = null;
Upvotes: 0
Reputation: 109232
The problem is that .each("end", ...)
is called for every element that you're selecting. That is, makeLinesThin
is called once for each line in makeLinesThick
. 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 using settimeout()
. Note in particular the documentation for transition.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.
Upvotes: 6