使用javaScript
的canvas
绘制简单的柱状图还是比较容易的,实现的效果图如下所示:

其实现原理就是首先绘制一条底线,然后在底线上根据传递的数据来绘制矩形,绘制矩形前,首先要找到数组中最大的value
值,再根据柱状图画布的高度来算出每一等份的值,然后就可以计算出每一个矩形的图形高度。然后再顶部和底部分别绘制出具体的数值和名称。具体实现代码如下所示:
function Bar(option) {
this._init(option)
}
Bar.prototype = {
_init:function (option) {
var container = option.container;
if(!container){
console.log('需要指定一个画布选择器');
return;
}
this.data = option.data || [];
this.canvas = document.getElementById(container);
this.ctx = this.canvas.getContext('2d');
var self = this;
// 获取最大值
this.data.forEach(function (item) {
if (!self.maxValue) {
self.maxValue = item.value;
} else if (item.value > self.maxValue) {
self.maxValue = item.value;
}
})
},
/*
* 绘制
* */
draw:function () {
var x = 50;
var y = this.canvas.height - 150;
var w = this.canvas.width - x * 2;
var h = y - 50;
//绘制底线
this.ctx.moveTo(x,y);
this.ctx.lineTo(w + x,y);
this.ctx.stroke();
var heightPercent = h / this.maxValue;//根据最大值计算出每一份的高度
var widthPercent = w / this.data.length;
var self = this;
this.data.forEach(function (item,index) {
var rectX = (1/4+index)*widthPercent;
var itemH = heightPercent * item.value;
//绘制矩形
self.ctx.fillStyle = item.color;
self.ctx.fillRect(rectX, y - itemH - 1, widthPercent * 0.5, itemH);
//绘制矩形上边的文字
self.ctx.font = '20px 宋体';
self.ctx.textAlign = 'center';
self.ctx.fillText(item.value, rectX + widthPercent / 4, y - itemH - 10);
self.ctx.save();
//绘制底部的文字
var textCanvas = document.createElement('canvas');
var textCtx = textCanvas.getContext('2d');
textCtx.font = '20px 宋体';
textCtx.textAlign = 'left';
textCtx.fillStyle = 'red';
textCtx.rotate(30 * Math.PI / 180);
textCtx.fillText(item.name, widthPercent/4,0);
self.ctx.drawImage(textCanvas,rectX, y + 10);
})
}
}
1.首先合建一个Bre
的函数,然后调用_init
方法。
2.在draw
方法中实现具体的绘制方法。先通过lineTo
绘制一条底线,然后再遍历数组,算出矩形的x
坐标,y
坐标,宽度和高度,再调用fillText
绘制矩形。然后将value
绘制到矩形的顶部。
3.底部的名称由于要旋转30度,所以单独作为一个canvas
来进行绘制。再通过drawImage
将文字添加到主画布上。
以下为HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>柱状图</title>
<style>
canvas{
border: 1px solid red;
}
</style>
</head>
<body>
<canvas id="chart" width="1000" height="500"></canvas>
</body>
<script src="./chart/Bar.js"></script>
<script>
var data = [
{name:'名称1',value:200,color:'red'},
{name:'名称2',value:80,color:'blue'},
{name:'名称3',value:120,color:'green'},
{name:'名称4',value:60,color:'orange'},
]
var bar = new Bar({
container:'chart',
data:data
});
bar.draw();
</script>
</html>
网友评论