How to update an svg path with d3.js

前端 未结 2 1626
情歌与酒
情歌与酒 2020-12-29 07:10

I\'d like to apply the \"general update pattern\" from official documentation to update an svg path on the mouse event (but could be a button or whatever).

But the t

2条回答
  •  星月不相逢
    2020-12-29 07:51

    Please try the following code, I think it's what you want. The problem is caused because you should distinguish enter, update and exit when you want to update elements, otherwise it will add data again and again.

    $(function() {
    var container = $('#container');
    
    // D3
    console.log("D3: ", d3);
    
    var svg = d3.select('#container')
                .append('svg:svg')
                .attr('height', 600)
                .attr('width', 800);
    
    var line = d3.svg.line()
                    .x(function(d) { return d[0]; })
                    .y(function(d) { return d[1]; })
                    .interpolate('linear');
    
    svg.data(shapeCoords)
        .append('svg:path')
        .attr('d', line(shapeCoords) + 'Z')
        .style('stroke-width', 1)
        .style('stroke', 'steelblue');
    
    function render() {
    
        var svg = d3.select('#container').select("svg").selectAll('path').data(shapeCoords);
        svg.enter().append('svg:path')
                .attr('d', line(shapeCoords) + 'Z')
                .style('stroke-width', 1)
                .style('stroke', 'steelblue');
        svg.attr('d', line(shapeCoords) + 'Z')
                .style('stroke-width', 1)
                .style('stroke', 'steelblue');    
        svg.exit().remove();    
    
    }
    render();
    

提交回复
热议问题