Chartjs-Adding image on chart js

1👍

Following is a CSS based solution. Please refer to this sample I have just created and edit the CSS as you prefer>> https://jsfiddle.net/0paz7Lqr/1/

HTML :

 <canvas id="chart" width="390" height="225"></canvas>

JS:

    var barData = {
    labels: ["John W", "Ben T", "Jenny H", "Samantha D", "Anothony P"],
    datasets: [
        {
            fillColor: "rgba(153, 153, 155, 0.4)",
            highlightFill: "#7C7C7C",
            strokeColor: "#7C7C7C",
            pointColor: "#7C7C7C",
            pointStrokeColor: "#7C7C7C",
            pointHighlightFill: "#fff",
            data: [25, 94, 68, 175, 66]
        }
    ]
};

var ctx = $("#chart").get(0).getContext("2d");
var myChart = new Chart(ctx).Line(barData);
    

CSS:

 canvas {
   background-image: url(https://homepages.cae.wisc.edu/~ece533/images/airplane.png);  
   background-size: 35% 25%;
   background-position: bottom 30px right 20px;  
   background-repeat: no-repeat;
}

0👍

You can use a custom plugin to draw the image on the canvas using the drawImage() method:

const image = new Image();
image.src = 'https://www.chartjs.org/img/chartjs-logo.svg';

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderColor: "pink"
    }]
  },
  options: {},
  plugins: [{
    id: 'customImage',
    beforeDraw: (chart) => {
      if (image.complete) {
        const ctx = chart.ctx;
        const {
          top,
          left,
          width,
          height
        } = chart.chartArea;
        const x = left + width - image.width;
        const y = top + height - image.height;
        ctx.drawImage(image, x, y);
      } else {
        image.onload = () => chart.draw();
      }
    }

  }]
}

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.4.1/chart.js"></script>
</body>

Leave a comment