Search code examples
javascripthtmlcsspngheatmap

How can I display an image on top of a generated heatmap?


I am trying to use heatmap.js to create a heatmap, following the instructions from this post: How to render heatmap.js on an image?

All of my code is identical to the one at that example. Just a simple generated heatmap with a background image added in CSS. Please see this screenshot from that post : The code I am using, from the previously mentioned post.

But I want to display an image on top of the heatmap, so a foreground image instead of a background image.

I have tried using plotly, but unfortunately this is intended to run on an ESP-32, with SPIFFS, so I am extremely limited to space and processing power. Even after I used the partial bundle to get the file size down small enough, the web page just simply wouldn't load. I'd really prefer to use heatmap.js if possible anyways, since it has a much smaller footprint.

To further explain what I'm trying to do, I want to put this half-transparent image on top of the generated heatmap:

The image I want to paint on top of the generated heatmap

So the final desired result would look like this, displaying only the heatmap inside the transparent part of the foreground image: Desired result, the blue inside the body is the heatmap.

All the code I am using is identical to the previously mentioned post, just a simple generated heatmap with a background image added in CSS. I also used this documentation here to build an example heatmap, https://www.patrick-wied.at/static/heatmapjs/docs.html

Is there any easy way to do this using HTML/CSS/JavaScript?


Solution

  • I don't know heatmap so cannot test this, but from the info given in the question if the placing of a background image works as shown then the placing of a foreground image should be possible.

    What we do is style an after pseudo element on #heatmap, give it the correct dimensions, put it above the heatmap element using z-index and give it the required image as its background. The image should then appear to be sitting above the heatmap element - I assume obscuring part of it.

    You need to make sure that the heatmap element is positioned so its after pseudo element knows where to position itself in relation.

    #heatmap {
      width: as you want
      height: as you want
      background-image: if you still want it to have one
      any other styling you want heatmap to have
    
      position: relative;
    }
    
    #heatmap::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 1; /* make sure this is big enough - higher than the heatmap's z-index */
      background-image: url(the image you want to be in the foreground);
      background-size: cover; /* or contain depending on what you want */
      background-repeat: no-repeat;
      background-position: center center; /*or wherever you want it */
    }
    

    }