Search code examples
javascripthtmlreactjsjsxhtml2canvas

How to generate a transparent canvas using html2canvas


this seems like it should be a simple thing but it's crazily difficult.

I simply have a div DOM element with some text inside.

I'm calling the html2canvas method on it and it's working find.

The only problem, the canvas has a white background!

I tried:

  • Setting the background property on the options object to null
  • Explicitly changing the CSS background property to transparent on the canvas and the DOM element that it was being generated from

Unfortunately nothing seems to work.

Hopefully there is an elegant solution but a quick hack is okay.


Solution

  • You must pass backgroundColor as null see: https://html2canvas.hertzen.com/configuration

    let el = document.querySelector("#my-div")
    html2canvas(el,{backgroundColor:null}).then(canvas => {
      document.body.appendChild(canvas)  
    })
    

    Working example: https://codepen.io/emilio/pen/oaGLmb?editors=1111