function drawBar(svgEle, option, arr) {
// svgEle 为父节点 svg 元素
// option 为样式设置选项
// arr 为需要渲染的数据
// 渲染柱状图
let type = "rect";
let updateBar = svgEle.selectAll(type).data(arr);
console.log(updateBar);
updateBar.attr("width", option.barW).attr("height", val => {
return val.value;
}).attr("fill", "red")
.attr("x", (val, i) => {
return 20 + i * option.barPlace;
}).attr("y", val => {
return 500 - val.value - 20;
});
// 数据大于元素节点
let enterBar = updateBar.enter();
// 处理数据大于元素时的情况
enterBar.append(type)
.attr("width", option.barW).attr("height", val => {
return val.value;
}).attr("fill", "red")
.attr("x", (val, i) => {
return 20 + i * option.barPlace;
}).attr("y", val => {
return 500 - val.value - 20;
});
// 元素节点大于数据
let exitBar = updateBar.exit();
exitBar.remove();
// 渲染柱状图名字
let updateTxt = svgEle.selectAll("text").data(arr);
updateTxt.attr("x", (val, i) => {
return 20 + i * option.barPlace + option.barW / 2;
}).attr("y", val => {
return 500 - val.value - 20;
}).text(data => {
return data.name;
}).attr("text-anchor", "middle").attr("fill", "#080");
let enterTxt = updateTxt.enter();
enterTxt.append("text")
.attr("x", (val, i) => {
return 20 + i * option.barPlace + option.barW / 2;
}).attr("y", val => {
return 500 - val.value - 20;
}).text(data => {
return data.name;
}).attr("text-anchor", "middle").attr("fill", "#080");
let exitTxt = updateTxt.exit();
exitTxt.remove();
}
let updateBar = svgEle.selectAll(type).data(arr);
let enterBar = updateBar.enter();
let exitTxt = updateTxt.exit();
exitTxt.remove();