[Chartjs]-Chart.js Custom Image for Each Point

12👍

var yourImage = new Image(),
    yourImage.src ='http://your.site.com/your_image.png';
data = {
      labels: ['one', 'two', 'three'],
      datasets: [{
        label: 'Label1',
        pointRadius: [0,0,0,0,20],
        pointHoverRadius: [0,0,0,0,20],
        pointHitRadius: [0,0,0,0,20],
        pointStyle: ['', '', '', '', yourImage],
        data: [1,2,3]
      }, {
        label: 'label2',
        pointRadius: [0,0,0,0,20],
        pointHoverRadius: [0,0,0,0,20],
        pointHitRadius: [0,0,0,0,20],
        pointStyle: ['', '', '', '', yourImage],
        data: [1,2,3]
      }]

8👍

Here is a more complete example. It shows how you can set styles for individual points or for all points.

  var yourImage = new Image()
  yourImage.src ='http://your.site.com/your_image.png';
  var imageData = {
    labels: ['one', 'two', 'three', 'four'],
    datasets: [{
      label: 'Label1',
      pointRadius: [10, 0, 10, 10],
      pointHoverRadius: 20,
      pointHitRadius: 20,
      pointStyle: ['rect', yourImage, 'triangle', 'circle'],
      pointBackgroundColor: "rgba(0,191,255)",
      data: [1.5, 2.3, 3, 2.5]
    }]
  }
  window.onload = function() {
    var lineID = document.getElementById('canvas').getContext('2d');
    var lineChart = new Chart(lineID, {
      type: 'line',
      data: imageData,
      options: {}
    });

4👍

I was trying to accomplish this in a Vue app (built with Webpack), and landed on the following solution. Import an image and create an image element like so:

import myIcon from '@/assets/my-icon.svg'

const chartPoint = new Image()
chartPoint.src = myIcon

Then in your chart.js dataset options (adjust to your needs):

{
  data: data,
  pointRadius: 10,
  borderWidth: 0,
  pointStyle: chartPoint,
...
}

drawImage() takes various types of image elements, but the easiest is just an HTMLImageElement, which you can create in your markup or with Javascript, as above.

Leave a comment