我们经常使用类似echarts这样的可视化图表,虽然提供给我们的生态已经够完善了,但是缺不能满足我们的自定义和好奇心,现在我们用简单的canvas来绘画柱状图(代码不想优化了建议用面向对象书写)
var heightc, widthc;
var w = document.getElementById("barChart")
var heightc = w.height - 50;
var widthc = w.width - 50;
var s = document.getElementById("barChart").getContext('2d');
s.beginPath();
s.moveTo(50, 0);
s.lineTo(50, heightc);
s.stroke();
s.beginPath();
s.moveTo(50, heightc);
s.lineTo(widthc, heightc);
s.stroke();
var heig = heightc;
var withdx = widthc / 6;
var top = 0;
for (var i = 0; i < 6; i++) {
var bar = (Math.random() * (500 - 1) + 1) / 2.04;
// 水平横线
s.beginPath();
s.strokeStyle = 'rgb(202,205,209)';
s.moveTo(50, heig);
s.lineTo(widthc, heig);
s.stroke();
// 柱形
s.beginPath();
s.fillStyle = randomColor();
s.fillRect(withdx, 350, 50, -bar);
s.stroke()
// y轴描述
s.beginPath();
s.fillStyle = '#000000'
s.font = "15px Arial";
s.fillText(top, 15, heig);
s.stroke()
// x轴描述
s.beginPath();
s.fillStyle = '#000000'
s.font = "15px Arial";
s.fillText(`${i+1}年`, withdx+10, 380);
s.stroke()
top += 102;
heig -= 50;
withdx += 80
}
}
function randomColor() {
var str = '#';
for (var i = 0; i < 6; i++) {
str += Math.floor(Math.random() * 16).toString(16);
}
return str;
}
效果图