Search code examples
javascripthtml2canvas

html2canvas cuts off image at the top left corner


I've got a map in my HTML and I'm using html2canvas to transform it into an image for printing.

This is the map in my HTML when I load my page:

enter image description here

This is the image I generate

enter image description here

using this code

var map = document.getElementById('FirstMap_CongestionDetail');

html2canvas(map, { scale: 0.5 }).then(canvas => {
    var imageData = canvas.toDataURL();
    //More code below
});

It appears to be cut off at the top left. It's not hidden (I've already checked padding, margin and overflow hidden).

This is the html code that generates the original image:

<div class="leafletMainMap spainCommunities leaflet-container leaflet-touch leaflet-retina leaflet-fade-anim" id="FirstMap_CongestionDetail" tabindex="0" style="position: relative; min-height: 0px; min-width: 0px; height: 553px;">

I checked the classes within the css file and none of them seem to be the problem.

I've seen issues with html2canvas related to content being cut off when trying to convert all HTML to canvas, and they are usually resolved by removing the scroll.

I already tried the following but didn't work:

https://github.com/niklasvh/html2canvas/issues/1438#issuecomment-739244530

I also tried to modify the height and width manually but it only makes the image bigger or smaller. It's still cut off.

Any idea why the image is being cut off?


Solution

  • After reading again the documentation, I found out you can move the content with parameters x and y:

    function getParams() {
      if(document.querySelector('.spainCommunities')) {
        return { width: 680, height: 500, x: -130, y: -60 };
      } 
      return { width: 420, height: 420, x: -92, y: -88 };
    }
    

    Problem solved!