// 自定义斜线图案背景函数 function createDiagonalPattern(color = ‘black’) { let shape = document.createElement(‘canvas’); shape.width = 10; shape.height = 10; let c = shape.getContext(‘2d’); c.strokeStyle = color; c.beginPath(); c.moveTo(2, 0); c.lineTo(10, 8); c.stroke(); c.beginPath(); c.moveTo(0, 8); c.lineTo(2, 10); c.stroke(); return c.createPattern(shape, ‘repeat’); } var barChartData = { labels: [“January”, “February”, “March”, “April”, “May”, “June”, “July”], datasets: [{ type: ‘bar’, // 柱状图类型 label: “Visitor”, // 访客数 data: [200, 185, 590, 621, 250, 400, 95], fill: false, backgroundColor: createDiagonalPattern(‘grey’), borderColor: ‘grey’, borderWidth: 1, hoverBackgroundColor: ‘#71B37C’, hoverBorderColor: ‘#71B37C’, yAxisID: ‘y-axis-1’ // 关联到左侧Y轴 }, { type: ‘line’, // 折线图类型 label: “Sales”, // 销售额 data: [51, 65, 40, 49, 60, 37, 40], fill: false, borderColor: ‘#2E41CF’, backgroundColor: ‘#2E41CF’, pointBorderColor: ‘#2E41CF’, pointBackgroundColor: ‘white’, pointHoverBackgroundColor: ‘#2E41CF’, pointHoverBorderColor: ‘#2E41CF’, pointStyle: ‘circle’, pointRadius: 10, pointHoverRadius: 15, pointBorderWidth: 3, yAxisID: ‘y-axis-2’ // 关联到右侧Y轴 }] }; window.onload = function() { var ctx = document.getElementById(“canvas”).getContext(“2d”); window.myBar = new Chart(ctx, { type: ‘bar’, // 默认图表类型,但数据集中的type会覆盖 data: barChartData, options: { responsive: true, tooltips: { mode: ‘index’, // 提示框模式,显示所有数据集信息 intersect: false, // 鼠标不需精确覆盖到元素 }, elements: { line: { fill: false // 折线图不填充区域 } }, scales: { xAxes: [{ // X轴配置 display: true, // 显示X轴 gridLines: { display: true // 显示X轴网格线 }, ticks: { display: true // 显示X轴刻度标签 } }], yAxes: [{ // 左侧Y轴 (访客数) type: “linear”, display: true, // !!! 关键:设置为 true 以显示轴和标签 position: “left”, id: “y-axis-1”, // 与 Visitor 数据集的 yAxisID 匹配 gridLines: { display: true // 显示
微信扫一扫
支付宝扫一扫