【问题标题】:How can I update data with javascript d3?如何使用 javascript d3 更新数据?
【发布时间】:2012-10-31 13:46:26
【问题描述】:

我正在制作一个带有不同圆圈的情节。每个圆圈都有固定的位置,但每个圆圈的大小可以通过 html 输入字段单独更改。

用于输入字段的代码是这样的:

<input type="text" id="size1" class="size" value="" style="width: 30px;">

我已将数据保存在此数据集中:

var dataset = [{name: "circle1", xpos: -413, ypos: 278, color: "black", radius: $('#size1').val(),},
            {name: "circle2", xpos: -161, ypos: 290, color: "black", radius: $('#size2').val(),}];

这是我画圆的方式:

function drawCircle () {
            svg.selectAll("circle").remove();
            svg.selectAll("circle")
               .data(dataset)
               .enter()
               .append("svg:circle")
               .attr("cx", function(d){
                        return xScale(d.xpos);})
               .attr("cy", function(d){
                        return yScale(d.ypos);})
               .attr("r", function (d){            
                        return rScale(d.radius);})                          
               .attr("fill", "rgb(100,0,0)")
               .attr("opacity", "0.7");
        }

最后我做了一个触发器,当某些东西发生变化时,圆圈会再次绘制:

$('.size').change(function(){
            radius = $(this).val(); 
            svg.selectAll("circle")
               .transition()
               .duration(750)
               .attr("r", function (d){            
                        return rScale(radius);})
        });

这样,当我更改#size1 或#size2 中的值时,两个圆圈都会用最后输入的值重新绘制。

我的问题是:如何更新数据集,让每个圈子都“听取”自己的输入字段?

【问题讨论】:

  • 如何确定“自己的圈子”?顺便说一句,将您的 radius 变量设为本地

标签: javascript jquery d3.js


【解决方案1】:

我假设您有多个输入字段。

当您对其中一个字段进行更改时可以做什么,重新创建数据集并重新绘制圆圈。

您的数据集的静态数据可以存储在输入的数据属性中。

像这样:

HTML

<input type="text" id="circle1" class="size" value="" style="width: 30px;" data-circle='{"name": "circle1", "xpos": -161, "ypos": 290, "color": "black" }'>

javascript

function drawCircles (dataset) {
        svg.selectAll("circle").remove();
        svg.selectAll("circle")
           .data(dataset)
           .enter()
           .append("svg:circle")
           .attr("cx", function(d){
                    return xScale(d.xpos);})
           .attr("cy", function(d){
                    return yScale(d.ypos);})
           .attr("r", function (d){            
                    return rScale(d.radius);})                          
           .attr("fill", "rgb(100,0,0)")
           .attr("opacity", "0.7");
    }

$('.size').change(function(){
        var dataset = [];
        $('.size').each(function(index,item) {
          var circleData = item.data('circle');
          var circleData['radius'] = $(item).val();
          dataset.push(circleData);
        });
        drawCircles(dataset);
    });

【讨论】:

    猜你喜欢
    • 2012-08-11
    • 2014-03-29
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 2015-12-15
    相关资源
    最近更新 更多