Kristian
Kristian

Reputation: 21830

How do I animate the thickness of a stroke in D3.js?

i've successfully added transitions to my circles in a node graph, but i'm now trying to animate the mouseover of the connective line.

here's what I've tried:

//define the lines:
var edges = svg.selectAll("line")
            .data(dataset.edges)
            .enter()
            .append("line")
            .style("stroke", "#ccc")
            .style("stroke-width", 1)
            .on("mouseover", lineMouseover)
            .on("mouseout", lineMouseout);

//the callback functions for mouseover / mouseout
function lineMouseover() {
    d3.select(this).select("line")
        .transition()
        .duration(100)
        .style("stroke-width", 3);
}
function lineMouseout() {
    d3.select(this).select("line")
        .transition()
        .duration(100)
        .style("stroke-width", 1);
}

Nothing seems to happen at all when i mouse over the lines. so, either i'm capturing the line incorrectly, or the attributes i'm animating are the wrong attributes.

any insight into what I'm doing wrong here?

Upvotes: 1

Views: 4640

Answers (1)

Pablo Navarro
Pablo Navarro

Reputation: 8264

In your code, the thiscontext in the lineMouseOverand lineMouseOut functions is the line element. You could simply use d3.select(this)to select each line and set its attributes. I wrote a small fiddle http://jsfiddle.net/pnavarrc/4fgv4/2

svg.selectAll('path')
   .data(data)
   .enter()
   .append('path')
   .attr('d', function(d) { return line(d.p); })
   .attr('stroke-width', function(d) { return d.w; })
   .attr('stroke', function(d) { return d.c; })
   .on('mouseover', mOver)
   .on('mouseout', function(d) {
       d3.select(this)
           .transition()
           .duration(300)
           .style('stroke-width', d.w);
    });

function mOver(d) {
    d3.select(this)
        .transition()
        .duration(300)
        .style('stroke-width', 6);
}

Regards,

Upvotes: 6

Related Questions