2013-11-16 2 views
0

Я пытаюсь настроить визуализацию в d3, где она делает разные вещи, в зависимости от того, что еще произошло. Так, например, я могу изменить цвет прямоугольника, и в зависимости от цвета прямоугольника другие функции ведут себя по-разному. Кроме того, я не могу заставить его работать.Использование атрибутов SVG в переменных в d3

Редактировать: Вот более полный пример того, что я пытаюсь сделать. У меня есть гистограмма, окрашенная в зеленый цвет. Нажмите кнопку, чтобы цвета были красными или синими, в зависимости от цвета другого окна, которое может быть красным или синим.

var dataset = [ 1,3,4,2,5]; 
var w = 600; 
var h = 500; 

var xScale = d3.scale.ordinal() 
         .domain(d3.range(dataset.length)) 
         .rangeRoundBands([0, w], 0.05); 

var yScale = d3.scale.linear() 
         .domain([0,10]) 
         .range([0, h]); 

         //Create SVG element 
     var svg = d3.select("body") 
        .append("svg") 
        .attr("width", w) 
        .attr("height", h); 

//this is how to change the colour of the box from red to blue and back again 



     svg.append("text") 
       .attr("x", 170) 
       .attr("y", 50) 
       .text("Make box red") 
       .attr("fill", "black") 
       .attr("id","clicktwo") 
       .on("mouseover",function() { 
    d3.select(this) 
.attr("cursor", "pointer");}) 







     svg.append("text") 
       .attr("x", 170) 
       .attr("y", 80) 
       .text("Make box blue") 
       .attr("fill", "black") 
       .attr("id","clickfour") 
       .on("mouseover",function() { 
    d3.select(this) 
.attr("cursor", "pointer");}) 

//here's a box you can change the colour of 

    svg.append("rect") 
.attr("x",350) 
.attr("y",60) 
.attr("width",50) 
.attr("height",30) 
.attr("fill","blue") 
.attr("stroke", "black") 
.attr("id","boxfive") 

// this is the variable i'm bothered about, set to the value of the colour of boxfive 

    var boxColour = svg.select("#boxfive") 
    .attr("fill");      


// click this one to make the bars match the colour of the box 



svg.append("text") 
      .attr("x", 5) 
       .attr("y", 50) 
       .text("Make bars match box") 
       .attr("fill", "black") 
       .attr("id","clickone") 
       .on("mouseover",function() { 
    d3.select(this) 
.attr("cursor", "pointer");}) 


/click this to reset the colour of the bars        


     svg.append("text") 
       .attr("x", 5) 
       .attr("y", 80) 
       .text("Reset bar colour") 
       .attr("fill", "black") 
       .attr("id","clickthree") 
       .on("mouseover",function() { 
    d3.select(this) 
.attr("cursor", "pointer");}) 






     svg.selectAll() 
      .data(dataset) 
      .enter() 
      .append("rect") 
      .attr("x", function(d, i) {    
         return xScale(i); 
        }) 
      .attr("y", function(d) { 
       return h-yScale(d); 
      }) 
      .attr("width", w/9) 
      .attr("height", function(d) { 
       return yScale(d); 
       }) 
      .attr("fill", "green") 
      .attr("id", "thenbars") 
       ; 


     d3.select("svg #clickone") 
      .on("click", function() {  

    svg.selectAll("svg #thenbars") 
    .data(dataset) 
     .transition()      
     .duration(500) 
     .attr("fill",function() { 
        if (boxColour = "red") {return "red"} 
     else { return "blue"} 
     ;}) 


     }); 

     //reset the bars to green 

    d3.select("svg #clickthree") 
      .on("click", function() {  

svg.selectAll("svg #thenbars") 
    .data(dataset) 
     .transition()      
     .duration(500) 
        .attr("fill","green")    
     }); 

    // and this is how you change the colour of the box 

     d3.select("svg #clicktwo") 
      .on("click", function() {     

     svg.select("svg #boxfive") 
.attr("fill","red") 

}); 

// and change it back 

     d3.select("svg #clickfour") 
      .on("click", function() {  

     svg.select("svg #boxfive") 
.attr("fill","blue") 
.attr("stroke","none") 

}); 
+1

Я бы сказал, что ваш селектор ничего не выбирает. Вероятно, вы хотите 'svg.select (« svg> #boxone »)' или, если 'svg' содержит ссылку на SVG уже,' svg.select ("# boxone") '. –

+0

Я понимаю, что вы имеете в виду, но это не похоже на это. Я добавил более подробно выше, теперь –

+0

Вы подтвердили, что он правильно выбирает? 'svg.select (" # boxone ")' должен это сделать. –

ответ

1

Вы должны установить boxColour переменную внутри обработчика click, в противном случае это установить только один раз и не обновляется при изменении цвета. Изменен jsfiddle here.

Смежные вопросы