Canvas background

In some use cases you would want a background image or color over the whole canvas. There is no built-in support for this, the way you can achieve this is by writing a custom plugin.

In the two example plugins underneath here you can see how you can draw a color or image to the canvas as background. This way of giving the chart a background is only necessary if you want to export the chart with that specific background. For normal use you can set the background more easily with CSSCanvas background - 图1 (opens new window).

Canvas background - 图2

config setup plugin

  1. const config = {
  2. type: 'doughnut',
  3. data: data,
  4. plugins: [plugin],
  5. };
  1. const data = {
  2. labels: [
  3. 'Red',
  4. 'Blue',
  5. 'Yellow'
  6. ],
  7. datasets: [{
  8. label: 'My First Dataset',
  9. data: [300, 50, 100],
  10. backgroundColor: [
  11. 'rgb(255, 99, 132)',
  12. 'rgb(54, 162, 235)',
  13. 'rgb(255, 205, 86)'
  14. ],
  15. hoverOffset: 4
  16. }]
  17. };
  1. // 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().
  2. const plugin = {
  3. id: 'custom_canvas_background_color',
  4. beforeDraw: (chart) => {
  5. const {ctx} = chart;
  6. ctx.save();
  7. ctx.globalCompositeOperation = 'destination-over';
  8. ctx.fillStyle = 'lightGreen';
  9. ctx.fillRect(0, 0, chart.width, chart.height);
  10. ctx.restore();
  11. }
  12. };

Canvas background - 图3

config setup plugin

  1. const config = {
  2. type: 'doughnut',
  3. data: data,
  4. plugins: [plugin],
  5. };
  1. const data = {
  2. labels: [
  3. 'Red',
  4. 'Blue',
  5. 'Yellow'
  6. ],
  7. datasets: [{
  8. label: 'My First Dataset',
  9. data: [300, 50, 100],
  10. backgroundColor: [
  11. 'rgb(255, 99, 132)',
  12. 'rgb(54, 162, 235)',
  13. 'rgb(255, 205, 86)'
  14. ],
  15. hoverOffset: 4
  16. }]
  17. };
  1. // 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().
  2. const image = new Image();
  3. image.src = 'https://www.chartjs.org/img/chartjs-logo.svg';
  4. const plugin = {
  5. id: 'custom_canvas_background_image',
  6. beforeDraw: (chart) => {
  7. if (image.complete) {
  8. const ctx = chart.ctx;
  9. const {top, left, width, height} = chart.chartArea;
  10. const x = left + width / 2 - image.width / 2;
  11. const y = top + height / 2 - image.height / 2;
  12. ctx.drawImage(image, x, y);
  13. } else {
  14. image.onload = () => chart.draw();
  15. }
  16. }
  17. };