一步一步去实现一个柱状图

image.png

1.画坐标

``````  ctx.translate(40, 500)
``````

``````  // 画y轴
ctx.moveTo(0, 0)
ctx.lineTo(0, -yaxisLength)
// y轴左边箭头
ctx.moveTo(0, -yaxisLength)
ctx.lineTo(-arrowLength, -(yaxisLength - arrowLength))
// y轴右边箭头
ctx.moveTo(0, -yaxisLength)
ctx.lineTo(arrowLength, -(yaxisLength - arrowLength))
``````

``````  // 画x轴
ctx.moveTo(0, 0)
ctx.lineTo(xaxisLength, 0)
// x轴上边箭头
ctx.moveTo(xaxisLength, 0)
ctx.lineTo(xaxisLength - arrowLength, -arrowLength)
// x轴下边箭头
ctx.moveTo(xaxisLength, 0)
ctx.lineTo(xaxisLength - arrowLength, arrowLength)
ctx.stroke()
``````

2.画柱子

`````` var data = [{
value: 200,
title: '第一季度',
startColor: 'red',
endColor: 'green'
},
{
value: 120,
title: '第二季度',
startColor: 'orange',
endColor: 'red'
},
{
value: 300,
title: '第三季度',
startColor: 'purple',
endColor: 'green'
},
{
value: 60,
title: '第四季度',
startColor: 'gray',
endColor: 'red'
}
]
data.unshift({
value: 0,
title: ''
})
``````

``````ctx.font = '20px Arial'
ctx.lineWidth = lineWidth
interval = xaxisLength / data.length
for (var i = 1, len = data.length; i < len; i++) {
ctx.beginPath()
ctx.strokeStyle = data[i].color
ctx.moveTo(interval * i, 0)
ctx.lineTo(interval * i, -data[i].value)
var y = -data[i].value - 20
var linearGradientObj = ctx.createLinearGradient(interval * i, 0, interval * i, -data[i].value)