标签:push ase meta floor set http ddl height add
零基础自学前端 D3.js 初体验03 柱状图+排序
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>d3</title>
</head>
<script src="https://d3js.org/d3.v4.min.js"></script>
<body>
<button type="button" name="button" onclick="mySort()">排序</button>
<button type="button" name="button" onclick="myAdd()">添加数据</button>
</body>
<script type="text/javascript">
var width = 1000,
height = 400,
dataset = [50, 90, 124, 86, 73, 64, 110, 107],
padding = {
top: 20,
right: 20,
bottom: 20,
left: 20
},
rectWidth = 30,
rectStep = 35;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
var rect = svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("fill", "red")
.attr("x", function(d, i) {
return padding.left + i * rectStep;
})
.attr("y", function(d) {
return height - padding.bottom - d;
})
.attr("width", rectWidth)
.attr("height", function(d) {
return d;
});
var text = svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.attr("fill", "aqua")
.attr("font-size", "14px")
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return padding.left + i * rectStep;
})
.attr("y", function(d) {
return height - padding.bottom - d
})
.attr("dx", rectWidth / 2)
.attr("dy", "1em")
.text(function(d) {
return d;
});
function draw() {
var updateRect = svg.selectAll("rect")
.data(dataset);
var enterRect = updateRect.enter();
var exitRect = updateRect.exit();
var updateText = svg.selectAll("text")
.data(dataset);
var enterText = updateText.enter();
var exitText = updateText.exit();
updateRect.attr("fill", "red")
.attr("x", function(d, i) {
return padding.left + i * rectStep;
})
.attr("y", function(d) {
return height - padding.bottom - d;
})
.attr("width", rectWidth)
.attr("height", function(d) {
return d;
});
enterRect.append("rect")
.attr("fill", "red")
.attr("x", function(d, i) {
return padding.left + i * rectStep;
})
.attr("y", function(d) {
return height - padding.bottom - d;
})
.attr("width", rectWidth)
.attr("height", function(d) {
return d;
});
exitRect.remove();
updateText.attr("fill", "aqua")
.attr("font-size", "14px")
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return padding.left + i * rectStep;
})
.attr("y", function(d) {
return height - padding.bottom - d
})
.attr("dx", rectWidth / 2)
.attr("dy", "1em")
.text(function(d) {
return d;
});
enterText.append("text")
.attr("fill", "aqua")
.attr("font-size", "14px")
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return padding.left + i * rectStep;
})
.attr("y", function(d) {
return height - padding.bottom - d
})
.attr("dx", rectWidth / 2)
.attr("dy", "1em")
.text(function(d) {
return d;
});
exitRect.remove();
}
?
function mySort() {
dataset.sort(d3.ascending);
draw();
}
function myAdd() {
dataset.push(Math.floor(Math.random() * 100));
draw();
}
</script>
</html>
零基础自学前端,你要的学习资料到了-498854752
标签:push ase meta floor set http ddl height add
原文地址:http://www.cnblogs.com/xsns/p/6834936.html