Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a transparent canvas using html2canvas [duplicate]

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.

like image 728
Benjamin Sampson Avatar asked Sep 12 '25 18:09

Benjamin Sampson


1 Answers

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

like image 62
emi Avatar answered Sep 15 '25 08:09

emi