-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy path08-transition-color.html
110 lines (83 loc) · 2.46 KB
/
08-transition-color.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Add color transitions</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style type="text/css">
.bar {
/* fill: steelblue; */ /* Moved control of 'fill' to JS code below */
stroke: none;
}
.highlight {
fill: red;
}
</style>
</head>
<body>
<script type="text/javascript">
//Define our random-number generator function
var _id_ = 0;
function generate() {
return {
index: _id_++,
value: 1000 * Math.random()
};
}
//Generate random data to use for the chart
var data = d3.range(100).map(generate);
//Set variables for desired size of chart
var w = 900,
h = 100,
bw = 9;
//Define a scale for y axis values
var yScale = d3.scaleLinear()
.domain([0, d3.max(data, function(d) { return d.value; })])
.range([0, 100]);
//Select the <body> and create a new SVG element
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h);
//Create a series of 'rect' elements within the SVG
svg.selectAll("rect.bar")
.data(data)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function(d, i) {
return i * bw;
})
.attr("width", bw - 1)
.attr("y", function(d) {
return h - yScale(d.value);
})
.attr("height", function(d) {
return yScale(d.value);
})
.attr("fill", "steelblue") // <-- Moved 'fill' from CSS to here, as an element attribute
.on("mouseover", function(d) {
d3.select(this).classed("highlight", true);
})
.on("mouseout", function(d) {
d3.select(this).classed("highlight", false);
});
//Define a new function that re-colors all the bars
function recolor() {
svg.selectAll("rect.bar")
.transition()
.duration(500)
.attr("fill", function() {
var r = Math.round(Math.random() * 255); //Choose random red, green, blue values
var g = Math.round(Math.random() * 255);
var b = Math.round(Math.random() * 255);
return "rgb(" + r + "," + g + "," + b + ")"; //Set fill to rgb value
});
}
//Execute the recoloring function every two seconds
d3.interval(recolor, 2000);
//NOTE: CSS styles override SVG attributes.
// So when you mouse over a bar, it still
// turns red, no matter what its SVG 'fill' is!
</script>
</body>
</html>