我在 Chart.JS 中撰寫了一個自定義條形圖,它在資料集懸停時通過在其上繪制筆劃來突出顯示條,問題是筆劃是在條上繪制的,而我會將其設定為類似于“背景顏色”。

就像條形是可見的,因為筆觸顏色不透明度設定為 0.05,而如果我將其設定為 1,顯然這些將不再可見。
代碼
class CustomBar extends Chart.BarController {
draw() {
super.draw(arguments);
if (this.chart.tooltip._active && this.chart.tooltip._active.length) {
const points = this.chart.tooltip._active[0];
const ctx = this.chart.ctx;
const x = points.element.x;
const topY = points.element.y 150;
const width = points.element.width;
const bottomY = 0;
ctx.save();
ctx.beginPath();
ctx.moveTo(x, topY * 100);
ctx.lineTo(x width * 1.3, bottomY);
ctx.lineWidth = width * 4.3;
ctx.strokeStyle = 'rgba(0, 0, 0, 0.05)';
ctx.stroke();
ctx.restore();
}
}
}
CustomBar.id = 'shadowBar';
CustomBar.defaults = Chart.BarController.defaults;
Chart.register(CustomBar);
uj5u.com熱心網友回復:
為此,您將需要一個自定義插件,您可以在其中指定要在繪制資料集之前繪制它。你可以這樣做:
Chart.register({
id: 'barShadow',
beforeDatasetsDraw: (chart, args, opts) => {
const {
ctx,
tooltip,
chartArea: {
bottom
}
} = chart;
if (!tooltip || !tooltip._active[0]) {
return
}
const point = tooltip._active[0];
const element = point.element;
const x = element.x;
const topY = -(element.height 150);
const width = element.width;
const bottomY = 0;
const xOffset = opts.xOffset || 0;
const shadowColor = opts.color || 'rgba(0, 0, 0, 1)';
ctx.save();
ctx.beginPath();
ctx.fillStyle = shadowColor;
ctx.fillRect(x - (element.width / 2) xOffset, bottom, width * 1.3 * 4.3, topY);
ctx.restore();
}
});
const options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'orange'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
backgroundColor: 'pink'
}
]
},
options: {
plugins: {
barShadow: {
xOffset: -10,
color: 'red'
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/420860.html
標籤:
下一篇:回圈遍歷陣列并根據元素組合陣列
