了解 enter(), exit() 及 data binding
修改 data 產生的方式,方便觀察。exit() 不移除,而是變紅色
了解 enter(), exit() 及 data binding
修改 data 產生的方式,方便觀察。exit() 不移除,而是變紅色
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
text { | |
font: bold 48px monospace; | |
} | |
.enter { | |
fill: green; | |
} | |
.update { | |
fill: #333; | |
} | |
.remove { | |
fill: red; | |
} | |
</style> | |
<body> | |
<script src="//d3js.org/d3.v3.min.js"></script> | |
<script> | |
var alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); | |
var a = "abcdefghijklmnopqrstuvwxyz".split(""); | |
var width = 960, | |
height = 500; | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height) | |
.append("g") | |
.attr("transform", "translate(32," + (height / 2) + ")"); | |
function update(data) { | |
// DATA JOIN | |
// Join new data with old elements, if any. | |
var text = svg.selectAll("text") | |
.data(data); | |
// UPDATE | |
// Update old elements as needed. | |
text.attr("class", "update"); | |
// ENTER | |
// Create new elements as needed. | |
text.enter().append("text") | |
.attr("class", "enter") | |
.attr("x", function(d, i) { return i * 32; }) | |
.attr("dy", ".35em"); | |
// ENTER + UPDATE | |
// Appending to the enter selection expands the update selection to include | |
// entering elements; so, operations on the update selection after appending to | |
// the enter selection will apply to both entering and updating nodes. | |
text.text(function(d) { return d; }); | |
// EXIT | |
// Remove old elements as needed. | |
if (data.length == 0) { | |
text.exit().remove(); | |
} else { | |
text.exit().attr("class", "remove"); | |
} | |
} | |
var next = (function(alphabet){ | |
var _a = alphabet; | |
var e = 0; | |
var s = 1; | |
return function() { | |
e += 2 * s; | |
if (e == 26 || e == 0) { | |
s *= -1; | |
} | |
return _a.slice(0, e).sort(); | |
} | |
})(a); | |
// The initial display. | |
//update(alphabet); | |
update(next()); | |
// Grab a random sample of letters from the alphabet, in alphabetical order. | |
setInterval(function() { | |
update(next()); | |
//update(d3.shuffle(alphabet) | |
// .slice(0, Math.floor(Math.random() * 26)) | |
// .sort()); | |
}, 500); | |
</script> |