2012-10-31 44 views
0

我正在用不同的圈子做一個陰謀。每個圓都有固定的位置,但每個圓的大小可以通過html輸入字段單獨更改。如何使用javascript d3更新數據?

的代碼使用輸入字段是這樣的:

<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中的值時,兩個圓都用上次輸入的值重繪。

我的問題是:我怎樣才能更新數據集的方式,每個圈子'聽'他自己的輸入字段?

+0

如何確定的 「自己的圈子裏」?順便說一句,使你的'半徑'變量本地 – Bergi

回答

0

我假設你有多個輸入字段。

當您對其中一個字段進行更改時,您可以執行哪些操作,重新創建數據集並重新繪製圓圈。

您的數據集的靜態數據可以存儲在輸入的數據屬性中。

像這樣:

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); 
    });