niklasvh / html2canvas

Screenshots with JavaScript
https://html2canvas.hertzen.com/
MIT License
30.55k stars 4.8k forks source link

Unexpected gray background in exported image #3192

Open lichever opened 2 months ago

lichever commented 2 months ago

Bug reports:

html2canvas is used in my react project and there is unexpected gray background in the exported images. image

Specifications:

html2canvas version tested with: ^v1.4.1 Browser & version: Chrome 127.0.6533.120 and Edge 127.0.2651.105 Operating system: win10

lichever commented 2 months ago

One solution is to add {scale : 2}. One drawback is it would zoom in the exported image. Also, I am not sure if users zoom out the UI, will it be still effective. Essentially, a better solution to this issue is to remove the boxShadow of the selected dom tree. Before calling html2canvas(copy_node), clone the selected dom tree, setBoxShadowNone, and append to the document.body. Then call html2canvas(copy_node). Do not forget: document.body.removeChild(copy_node) in the html2canvas promise. This solution perfectly resolved the issue, and it was tested in Chrome and Edge browsers.

// remove the boxShadow of the selected dom tree
const setBoxShadowNone = (element) => {
  const stack = [element];

  while (stack.length > 0) {
    const currentElement = stack.pop();
    currentElement.style.boxShadow = 'none';

    for (let i = 0; i < currentElement.children.length; i += 1) {
      stack.push(currentElement.children[i]);
    }
  }
};