前言
媳妇公司有个需求,就是画立体柱状图的图表,本想使用hightcharts 画,效果和设计图出入太大,立体柱状图还需要渐变色,以及平面状态下展示立体效果,因此找到我帮忙画一个。
一、先上效果图
二、代码
dom结构
<div>
<div id="mainbar" class="mainbar"></div>
</div>
css样式
.mainbar {
height: 400px;
width: 800px;
}
js
let barWidth = 30
let wrapHeight = 400
let gridTop = 50
let gridBottom = 50
let innerHeight = wrapHeight - gridTop - gridBottom
let data1 = [120, 200, 150, 80, 70, 110, 130]
let max = Math.max(...data1)
let rat = innerHeight / max
function calcDecal(v) {
return {
symbol: 'image://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAMAAAC7IEhfAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAB4UExURQspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspUwspU7PIAhkAAAAndFJOU2N6W6KKa0xEqpqDsZJzVMABLym5PQQdIscIDRI2F9TO4dvm7PHw9Z3ihroAAAAJcEhZcwAAAEgAAABIAEbJaz4AAABlSURBVDjLjcEJAoEAAADBlS4pFEVK6dL/f+gLO8NNopZoJd4SncRHopF4SlQSpUQv8ZBIJGKJi0QgoUUShcRBIpMIJXKJk8RRIpU4S9wlrhIviVFikJgkvhKzxCKxSvwkdolN+gMv4nnh74YU4wAAAABJRU5ErkJggg==',
dashArrayX: [barWidth, 0],
dashArrayY: [gridTop + rat * (max - v), 0, rat * v],
symbolKeepAspect: false,
maxTileWidth: 10000,
maxTileHeight: 10000,
}
}
function calcColor(colors = []) {
return {
type: 'linear',
x: 0, x2: 1, y: 0, y2: 0,
colorStops: [
{
offset: 0,
color: colors[0] || '#055d84'
},
{
offset: 0.5,
color: colors[1] || '#0092c1'
},
{
offset: 0.5,
color: colors[2] || '#00c6fe'
},
{
offset: 1,
color: colors[3] || '#01baf5'
}
]
}
}
function renderBar() {
let chartDom = document.getElementById('mainbar');
let myChart = echarts.init(chartDom);
let option;
option = {
backgroundColor: '#0b2953',
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
grid: {
top: gridTop,
bottom: gridBottom,
},
legend: {
top: 0,
right: 10,
textStyle: {
color: '#ffffff'
}
},
series: [
{
name: '待处理',
type: 'bar',
barWidth: barWidth,
data: data1.map(v => {
return {
value: v,
itemStyle: {
decal: calcDecal(v)
}
}
}),
itemStyle: {
color: calcColor(),
},
},
{
name: '待处理',
z: 3,
type: 'pictorialBar',
symbolPosition: 'end',
data: data1,
symbol: 'diamond',
symbolOffset: ['0', '-50%'],
symbolSize: [barWidth, barWidth * 0.4],
itemStyle: {
normal: {
color: '#00ddfe',
},
},
}
]
};
option && myChart.setOption(option);
setTimeout(()=>{
myChart.resize()
}, 10)
}
renderBar()
三、原理简单介绍
1.渲染一个基础的柱状图图表 2.柱状图颜色使用线性渐变(横向渐变模拟立体柱子) 3.顶部是用 pictorialBar 模拟柱状图上表面 4.通过贴图花纹(echarts5 新增)设置上下渐变色 4.2 单个立体柱状图上下渐变色可通过叠加柱子的方式实现,如下面第二个例子
四、DEMO
1.立体柱状图,支持多个
2.单个立体柱状图简单版
总结
如果只有单个柱状图,也可以通过两个柱状图叠加的方式设置上下渐变色,就像第二个例子演示的方式。第一种可以设置多个柱状图,缺点是点击图例隐藏显示时 pictorialBar 会存在对不齐的方式。可以在切换时重新设置,这里就不写了。
以上信息如有疏漏或错误,欢迎指正
|