我正在尝试在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")
});