Overlay Images in Stacked Bar Chart | CanvasJS

Overlay images over the bars of all datapoints across dataseries in stacked bar chart

by canvasjs

HTML

<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>

CSS

.chart-image-overlay {
  pointer-events: none;
}

JavaScript

var imageArray = [];
var chart = new CanvasJS.Chart( "chartContainer", {
  theme: "light2",
  title :{
    text: "Overlay Bars with Images"
  },
  data: [{
    type: "stackedBar",
    imgUrl: "https://images.unsplash.com/photo-1576428596548-600696565a5e?jpg=format&fit=crop&w=277&q=80",
    dataPoints: [
      { y: 2 },
      { y: 3 },
      { y: 4 },
      { y: 10 },
      { y: 3 }
    ]
  },{
    type: "stackedBar",
    imgUrl: "https://images.unsplash.com/photo-1617957796155-72d8717ac882?jpg=format&fit=crop&w=277&q=80",
    dataPoints: [
      { y: 2 },
      { y: 3 },
      { y: 4 },
      { y: 10 },
      { y: 3 }
    ]
  },{
    type: "stackedBar",
    imgUrl: "https://images.unsplash.com/photo-1613832288685-5c81e86f89a5?jpg=format&fit=crop&w=277&q=80",
    dataPoints: [
      { y: 2 },
      { y: 3 },
      { y: 4 },
      { y: 10 },
      { y: 3 }
    ]
  }]
});

chart.render();
var noOfDps = 0;
for(var i = 0; i < chart.data.length; i++)
  if(chart.data[i].dataPoints.length > noOfDps)
    noOfDps = chart.data[i].dataPoints.length;

chart.set("dataPointWidth", Math.abs(chart.axisX[0].bounds.y2 - chart.axisX[0].bounds.y1) / noOfDps * .8);

addImages();

function addImages() {
  var dataSeries, 
      image,
      imageContainer = document.createElement("div");

  imageContainer.setAttribute("id", "image-container");
  imageContainer.style.cssText = "position: absolute; display: block";

  for(var i = 0; i < chart.data.length; i++) {
    dataSeries = chart.options.data[i];
    imageArray[i] = [];
    for(var j = 0; j < dataSeries.dataPoints.length; j++) {
      image = document.createElement("img");
      image.setAttribute("src", dataSeries.imgUrl);
      image.setAttribute("class", "chart-image-overlay");
      image.style.cssText ="position: absolute; display: block";
      imageContainer.appendChild(image);
      imageArray[i].push(image);

      positionImage(image, i, j);
    }
  } 

 ...