Open In App

Chart.js Canvas background Configuration

Last Updated : 08 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Chart.js Canvas Background Configuration consists of setting options to control the visual appearance of the chart area. We can implement the custom plugin through which we can provide the color or the image as the background for the Canvas area.

Syntax:

// Syntax for a basic Chart.js background plugin
Chart.plugins.register({
beforeDraw: function(chart) {
// Your background drawing logic here
// Use chart.ctx for canvas context operations
}
});

CDN link:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.1.2/chart.umd.js"></script>

Example 1: In the below example, we have created a bar chart with data related to GeeksforGeeks Programming Languages. We have used the custom plugin “backgroundColorPlugin” which is used to set the background canvas color.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width,
                     initial-scale=1.0">
    <title>Bar Chart with Custom Background Color</title>
    <script src=
    </script>
    <script src=
    </script>
</head>
 
<body>
    <div>
        <h1 style="color:green;">
              GeeksforGeeks
          </h1>
        <h3>
              Chart.js Canvas background
              Configuration - Color
          </h3>
        <div>
              <canvas id="barChart" width="400"
                     height="400">
            </canvas>
          </div>
    </div>
    <script>
        const data = {
            labels: ['Java', 'Python', 'C++',
                     'JavaScript', 'C#', 'PHP'],
            datasets: [{
                label: 'Programming Languages',
                data: [1, 2, 3, 4, 5, 6],
                backgroundColor: [
                    'rgba(255, 99, 132, 0.5)',
                    'rgba(54, 162, 235, 0.5)',
                    'rgba(255, 205, 86, 0.5)',
                    'rgba(75, 192, 192, 0.5)',
                    'rgba(153, 102, 255, 0.5)',
                    'rgba(255, 159, 64, 0.5)'
                ],
                borderColor: [
                    'rgba(255, 99, 132, 1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 205, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }]
        };
        const backgroundColorPlugin = {
            id: 'customCanvasBackgroundColor',
            beforeDraw: (chart) => {
                const ctx = chart.ctx;
                ctx.fillStyle = 'rgba(220, 220, 0, 0.5)';
                ctx.fillRect(0, 0, chart.width, chart.height);
            }
        };
        const config = {
            type: 'bar',
            data: data,
            plugins: [backgroundColorPlugin],
            options: {
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        };
        let ctx = document.getElementById('barChart')
                          .getContext('2d');
        let myBarChart = new Chart(ctx, config);
    </script>
</body>
 
</html>


Output:

Output1

Example 2: In the below example, we have used the Doughnut chart to represent the Data related to GeeksforGeeks. We have created a custom plugin named as ‘custom CanvasBackgroundImage‘ which uses the background image as the GeeksforGeeks logo applied to Canvas.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Doughnut Chart with Custom Background Image</title>
    <script src=
    </script>
    <script src=
    </script>
</head>
 
<body>
    <div>
        <h1 style="color:green;">
              GeeksforGeeks
          </h1>
        <h3>
              Chart.js Canvas background
              Configuration - Image
          </h3>
        <div>
              <canvas id="doughnutChart" width="700"
                     height="250">
            </canvas>
          </div>
    </div>
    <script>
        const data = {
            labels: ['Java', 'Python', 'JavaScript'],
            datasets: [{
                label: 'Programming Languages',
                data: [300, 50, 100],
                backgroundColor: ['rgb(255, 99, 132)',
                                  'rgb(54, 162, 235)',
                                  'rgb(255, 205, 86)'],
                hoverOffset: 4
            }]
        };
        const image = new Image();
        image.src =
        image.width = 250;
        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, image.width, image.height);
                } else {
                    image.onload = () => chart.draw();
                }
            }
        };
        const config = {
            type: 'doughnut',
            data: data,
            plugins: [plugin]
        };
        const ctx = document.getElementById('doughnutChart')
                            .getContext('2d');
        const myDoughnutChart = new Chart(ctx, config);
    </script>
</body>
 
</html>


Output:

Output2



Previous Article
Next Article

Similar Reads

How to Set Chart Title and Name of X Axis and Y Axis for a Chart in Chart.js ?
In this article, we will learn how to set the title, the name of the x-axis, and the name of the y-axis for a chart using the ChartJS CDN library. Approach:In the HTML template, use the &lt;canvas&gt; tag to show the line graph.In the script section of the code, instantiate the ChartJS object by setting the type, data, and options properties of the
3 min read
Chart.js Title Configuration
In this article, we will learn the concept of Chart.Js Title Configuration by using the Chart.js CDN library, along with understanding their basic implementation through the illustrations. In Chart.js, Title Configuration is mainly the config option to customize and manage the title of the chart. There are different types of configurations that are
5 min read
Chart.js Subtitle Configuration
In this article, we will learn the concept of Chart.Js Subtitle Configuration by using the Chart.js CDN library, along with understanding their basic implementation through the illustrations. In Chart.js, Subtitle Configuration is mainly the second title which is placed, by default, under the main title. The configuration options for subtitles are
4 min read
Chart.js Tooltip Configuration
When a user hovers over a data point in Chart.js, tooltips are visual UI components that offer additional information about the data point. By default, tooltips will show the label and value of the data point, but you may edit them to alter their appearance (styles) or to show different information depending on the user. In this article, we will se
5 min read
Chart.js Locale Configuration
Chart.js Locale Configuration facilitates the locale option in order to set the numbers of ticks on scales in accordance with language-specific number convention formatting. The locale is represented as a character sequence conforming to the Unicode BCP 47 locale identification standard. A language code.(Optionally) a script code(Optionally) a regi
2 min read
Chart.js Animations Configuration
Chart.js Animations Configuration is the set of options to control the dynamic visualization effects in the Chart.js chart. This configuration contains animation settings, transitions, easing functions, and more customizations like duration, and style etch. Using this configuration in Chart.js, we can make the chart more visually engaging and inter
4 min read
Chart.js Device Pixel Ratio Configuration
Chart.js Device Pixel Ratio Configuration option allows the users to override the default pixel ratio of the window, which provides control over the rendering resolution of the chart canvas. Syntax:const config = { options: { devicePixelRatio: 2 // Set your ratio value }, // Other chart configurations};Device Pixel Ratio Configuration OptionsBelow
3 min read
Chart.js Data Decimation Configuration
Chart.js Data Decimation is the feature developed for line charts, allowing us to reduce the data points automatically. By this, the chart's performance and visuals are optimized in proper clear form. Syntax:options: { plugins: { decimation: { algorithm: 'lttb', or 'min-max' // Other configuration options } } }Data Decimation Configuration Optionse
3 min read
Chart.js Elements Configuration
Chart.js Elements Configuration provides us with the option to configure four types of elements: arcs, lines, points, and bars. Developers can use the options provided by Elements Configuration to customize these elements to change the appearance and behavior of the charts that meet their requirements. Syntax: let ctx = document.getElementById('myC
5 min read
Chart.js Configuration
Chart.js Configuration is used to change the behavior and display of the chart according to the properties. There are many properties to change the display style, font, size, labels, and so on. The type, data, options, and plugin are required parameters for the chart.js configuration. The option and plugin are used to get attractive charts and othe
3 min read