Chart.js柱状图中是否可实现示例所示的彩色交叉线效果
Chart.js 柱状图彩色交叉线效果实现
完全可以实现你图中所示的交叉线效果,不需要依赖第三方插件,用Chart.js自带的自定义绘制能力就能完成。
效果参考图:
实现逻辑
- 这类交叉线不是通过修改柱状图原生配置实现的,是在柱状图本身绘制完成后,通过Chart.js的插件钩子拿到canvas上下文,手动在柱子区域绘制彩色交叉线条
- 绘制时可以直接拿到每个柱子的坐标、宽高参数,计算线条路径即可,不会影响原有柱状图的交互、图例、坐标轴等功能
- 线的颜色、粗细、密度都可以按需调整
适配你现有代码的完整实现
你不需要修改原有柱状图的数据、基础配置,只需要提前注册一个自定义绘制插件即可,代码如下:
// 注册交叉线自定义绘制插件 Chart.plugins.register({ afterDatasetsDraw: function(chart) { const ctx = chart.ctx; // 遍历所有数据集的柱子元素 chart.data.datasets.forEach((dataset, datasetIndex) => { const meta = chart.getDatasetMeta(datasetIndex); if (meta.hidden) return; // 跳过隐藏的数据集 meta.data.forEach((bar, index) => { const value = dataset.data[index]; if (value <= 0) return; // 无数值的柱子不绘制 // 获取当前柱子的位置、尺寸参数 const {x, y, base, width} = bar.getProps(['x', 'y', 'base', 'width']); const barTop = y; const barBottom = base; const barLeft = x - width / 2; const barHeight = barBottom - barTop; const barWidth = width; ctx.save(); // 交叉线样式配置 ctx.strokeStyle = dataset.backgroundColor; // 默认和柱子同色,可自定义 ctx.lineWidth = 2; // 线条粗细 const lineGap = 8; // 线条间距,数值越小线越密 ctx.beginPath(); // 绘制第一组右斜线 for (let offset = -barHeight; offset < barWidth; offset += lineGap) { ctx.moveTo(barLeft + offset, barBottom); ctx.lineTo(barLeft + offset + barHeight, barTop); } // 绘制第二组左斜线,形成交叉效果 for (let offset = 0; offset < barWidth + barHeight; offset += lineGap) { ctx.moveTo(barLeft + offset, barBottom); ctx.lineTo(barLeft + offset - barHeight, barTop); } ctx.stroke(); ctx.restore(); }) }) } }) // 你原有的柱状图代码无需修改 var ctx = document.getElementById("mybarChart").getContext("2d"); var mybarChart = new Chart(ctx, { type: 'bar', data: { labels: ['1', '2', '3'], datasets: [{ label: 'Candidate A Votes', backgroundColor: "#000080", data: [90,0,0] }, { label: 'Candidate B Votes2', backgroundColor: "#d3d3d3", data: [0,70,0] }, { label: 'Candidate C Votes3', backgroundColor: "#add8e6", data: [0,0,45] }] }, options: { legend: { display: true, position: 'top', labels: { fontColor: "#000080", } }, scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } });
自定义调整说明
- 要调整交叉线疏密,修改
lineGap的数值即可,数值越大线条越稀疏 - 要调整线条粗细,修改
ctx.lineWidth的数值 - 如果需要交叉线和柱子颜色不同,直接给
ctx.strokeStyle赋值目标色值即可 - 如果只需要单方向斜线,删掉其中一组循环绘制线条的代码就行
- 如果你用的是Chart.js 3.x以上版本,插件注册需要改用
Chart.register()方法,核心绘制逻辑不变
内容的提问来源于stack exchange,提问作者Raphael
相关产品推荐
相关产品推荐

