Search code examples
javascripthtmlcsshtml2canvasdocument-body

taking screenshot of hidden element using html2canvas after modifying style


Would like to take a screenshot of a div inside the document body (to be saved as PDF) but I would like to clone it first, hide it from being on the page and manipulate it stylewise before being rendered by html2canvas. Problem is the div is showing on the page with the CSS manipulation (but it should never show at all). What's the correct way to do it?

Have to add the element to body first otherwise I would get this error Uncaught (in promise) Unable to find element in cloned iframe

The other problem is if I do hide the opacity or set visibility none of the cloned div, then the saved PDF will have nothing inside


const myNodeCopy = document.body
    .querySelector("#myDiv")
    ?.cloneNode(true);

document.body.append(myNodeCopy as Node);

(myNodeCopy as HTMLElement).setAttribute(
    "style",
    "background-color: white; color: black;"
  );

  // problem if setting styles to opacity 0 or visilibity none because exported pdf will be empty
  // 

html2canvas(mydiv, {
    onclone: function (clonedDoc) {
        
    }
}).then((canvas)=>{
     // add image to JsPDF 

     // remove the cloned div from document body
})

Solution

  • Perhaps instead of appending the copied node to the end, you prepend it to the beginning of the document using document.body.prepend(myNodeCopy as Node); and set its positioning as absolute in the styling. Then the rest of the page should be able to overlap it (cover it up) while you perform the rest of your operations. You may also need to consider the stacking context to ensure the elements are stacked in the proper order.