Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callbacks with D3

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.

like image 618
djq Avatar asked Jun 29 '26 00:06

djq


2 Answers

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.

like image 79
Lars Kotthoff Avatar answered Jul 01 '26 15:07

Lars Kotthoff


use .each("start") and .each("end") to set your transitions

like image 33
bailey Avatar answered Jul 01 '26 13:07

bailey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!