# 畫布背景
在某些使用情況下,您可能希望在整個畫布上顯示背景圖片或顏色。目前沒有內建支援此功能,您可以使用自訂外掛程式來實現。
在下方兩個外掛程式範例中,您可以看到如何將顏色或圖片繪製到畫布作為背景。只有在您想要匯出具有該特定背景的圖表時,才需要這種為圖表提供背景的方式。對於正常使用,您可以更輕鬆地使用 CSS (在新視窗中開啟) 設定背景。
const config = { type: 'doughnut', data: data, options: { plugins: { customCanvasBackgroundColor: { color: 'lightGreen', } } }, plugins: [plugin], };
const data = { labels: [ 'Red', 'Blue', 'Yellow' ], datasets: [{ label: 'My First Dataset', data: [300, 50, 100], backgroundColor: [ 'rgb(255, 99, 132)', 'rgb(54, 162, 235)', 'rgb(255, 205, 86)' ], hoverOffset: 4 }] };
// Note: changes to the plugin code is not reflected to the chart, because the plugin is loaded at chart construction time and editor changes only trigger an chart.update(). const plugin = { id: 'customCanvasBackgroundColor', beforeDraw: (chart, args, options) => { const {ctx} = chart; ctx.save(); ctx.globalCompositeOperation = 'destination-over'; ctx.fillStyle = options.color || '#99ffff'; ctx.fillRect(0, 0, chart.width, chart.height); ctx.restore(); } };
const config = { type: 'doughnut', data: data, plugins: [plugin], };
const data = { labels: [ 'Red', 'Blue', 'Yellow' ], datasets: [{ label: 'My First Dataset', data: [300, 50, 100], backgroundColor: [ 'rgb(255, 99, 132)', 'rgb(54, 162, 235)', 'rgb(255, 205, 86)' ], hoverOffset: 4 }] };
// Note: changes to the plugin code is not reflected to the chart, because the plugin is loaded at chart construction time and editor changes only trigger an chart.update(). const image = new Image(); image.src = 'https://chartjs.dev.org.tw/img/chartjs-logo.svg'; const plugin = { id: 'customCanvasBackgroundImage', beforeDraw: (chart) => { if (image.complete) { const ctx = chart.ctx; const {top, left, width, height} = chart.chartArea; const x = left + width / 2 - image.width / 2; const y = top + height / 2 - image.height / 2; ctx.drawImage(image, x, y); } else { image.onload = () => chart.draw(); } } };