[英]How to fill the area between two vertical lines in the chart using chartjs library?
我需要使用 chartjs 填充兩個折線圖之間的區域。 我找到了當你有一條線在另一條線之上時如何做到這一點,但我想知道你什么時候有兩條線並排並且我需要它們之間的區域。
例如,像這樣的圖形的面積
代碼是這樣的:
const ctx = document.getElementById('myChart');
const myChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
label: 'linha 1',
data:[
{x: -11, y: 7},
{x: -11, y: 7},
{x: -1, y: 8},
],
showLine: true,
borderColor: '#009999',
backgroundColor: '#009999',
},
{
label: 'linha 2',
data: [
{x: 0, y: 7},
{x: 0, y: 7},
{x: 8, y: 8},
],
showLine: true,
borderColor: '#f00',
backgroundColor: '#f00',
}
]
},
options: {
responsive: false,
}
});
我認為你需要一個專用的插件來做到這一點。
我已經創建了一個(它可以改進),見片段。
const plugin = { id: 'myfill', beforeDatasetsDraw(chart, args, options) { const {ctx, data} = chart; ctx.save(); ctx.fillStyle = 'rgba(47, 98, 156, 0.2)'; ctx.beginPath(); let meta = chart.getDatasetMeta(0); let e = meta.data[0]; ctx.moveTo(ex, ey); e = meta.data[1]; ctx.lineTo(ex, ey); meta = chart.getDatasetMeta(1); e = meta.data[1]; ctx.lineTo(ex, ey); e = meta.data[0]; ctx.lineTo(ex, ey); ctx.fill(); ctx.restore(); } }; const ctx = document.getElementById('myChart'); const myChart = new Chart(ctx, { type: 'scatter', plugins: [plugin], data: { datasets: [{ label: 'linha 1', data:[ {x: -11, y: 7}, {x: -1, y: 8}, ], showLine: true, borderColor: 'rgb(47, 98, 156)', }, { label: 'linha 2', data: [ {x: 0, y: 7}, {x: 8, y: 8}, ], showLine: true, borderColor: 'rgb(47, 98, 156)', } ] }, options: { responsive: false, } });
.myChartDiv { max-width: 600px; max-height: 400px; }
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script> <html> <body> <div class="myChartDiv"> <canvas id="myChart" width="600" height="400"/> </div> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.