Search code examples
javascripthtmlcsshtml2canvas

html2canvas is not reading inline background-color style


I am using html2canvas which works great except the background colour of the div is not being read when I use inline styling. However it does work when a style sheet is used, but as the colour is controlled by react, I need it to read the inline style preferably, can anyone help fix this pls?

My html:

<div id="testDiv" class="page" style="width: 530px; height: 630px; background-color: red; position: relative;">...</div>

My js:

function getThumbnail = (div) => {
  return html2canvas(div).then(canvas => {
    return canvas.toDataURL();
  });
}

The image is rendered with no background in the above code unless I add:

#testDiv {
  background-color: red;
}

in a style sheet but then it is not easy to make the background variable.

UPDATE: I've also tried using css variables but html2canvas does not pick up this styling either.

:root {
  --garment-colour: #000000;
};

#testDiv {
  background-color: var(--garment-colour);
}

Solution

  • It does show the background. See console log for image data.

    html2canvas(document.querySelector("#testDiv")).then(canvas => {
        console.log(canvas.toDataURL());
    });
    

    Here is the fiddle: https://jsfiddle.net/nxrvsphz/