[Chartjs]-Style individual points from one dataset in Chart.js

4👍

You can add different images via an array.

//Create the image    
const img = new Image(20, 20);
img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1a/Skull_Icon_%28Noun_Project%29.svg/1200px-Skull_Icon_%28Noun_Project%29.svg.png";
const img2 = new Image(20, 20);
img2.src = "https://pngimg.com/uploads/pacman/pacman_PNG21.png";
const img3 = new Image(20, 20);
img3.src = "https://pngimg.com/uploads/pacman/pacman_PNG70.png"
var ctx = document.getElementById('chart').getContext('2d');


var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: "Deaths",
      data: [{
        x: "00:01:23",
        y: 0
      }, {
        x: "00:03:41",
        y: 0
      }, {
        x: "00:04:29",
        y: 0
      }, {
        x: "00:05:35",
        y: 0
      }, {
        x: "00:06:27",
        y: 0
      }, {
        x: "00:07:07",
        y: 0
      }, {
        x: "00:08:48",
        y: 0
      }, {
        x: "00:09:31",
        y: 0
      }],
      //Assign the image in the point Style attribute
      pointStyle: [img2, img, img3],

      showLine: false,
      fill: false,
      tooltip: "Player Died",
      borderColor: "#000000",
      backgroundColor: "#000000"
    }, ]
  },
  //The Rest is just styling
  options: {
    interaction: {
      mode: 'nearest'
    },
    tooltips: {
      custom: function(tooltip) {
        if (!tooltip) return;
        tooltip.displayColors = false;
      },
      callbacks: {
        title: function(tooltipItem, data) {
          return data.datasets[tooltipItem[0].datasetIndex]['tooltip'];
        },
        label: function(tooltipItem, data) {
          return tooltipItem.xLabel;
        }
      }
    },
    legend: {
      display: true
    },
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          parser: 'hh:mm:ss',
          tooltipFormat: 'HH:mm:ss',
          displayFormats: {
            second: "HH:mm:ss"
          },
          unitStepSize: 30
        },
        ticks: {
          fontColor: "white"
        }
      }],
      yAxes: [{
        ticks: {
          display: false,
        },
        gridLines: {
          display: false
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
<canvas id="chart" height="50px" style="background-color: rgb(200, 200, 200);"></canvas>

How you get the images to the array is up to you.

You can update it with something like this

function addimage(img) {
  myChart.data.datasets[0].pointStyle.push(img);
  myChart.update();
};
addimage(img2)

Of course you will want to add your images in some other dynamic way I’m sure but this should help.

Leave a comment