Element is not attached to a document html2canvas

Viewed 1538

What is the meaning of this error? and how to fix it

I try convert html data to canvas with html2canvas.

my code:

 html2canvas(ReactHtmlParser(pages[a])).then(function(canvas) {
     console.log(canvas);
 });
1 Answers

So basically what you want to do is to get a canvas from your react DOM.

Now what you should do is to give normal DOM to html2canvas(normalHTMLDomFromJS).

But what you are doing is to pass reactDOM(wich is javascript plain objects) to html2canvas

Element is not attached to a document html2canvas happens when you pass something except jsDOM to html2canvas(shouldNotBeJSDOMToThrowError) which means that ReactHtmlParser(pages[a]) is not returning js DOM(its returning react DOM(something like {}))

I suppose You are doing this is a react app so you must get a ref from your element then you can access your normal js DOM from ref.current

github issue

import React, { useRef } from "react";
import html2canvas from "html2canvas";
import ReactDOM from "react-dom";

function captureScreenshot(rootElem) {
    alert("Now.. Preparing Screenshot");
    console.log(rootElem);

    html2canvas(rootElem).then(canvas => {
        document.body.appendChild(canvas);
    });
}

function App(props) {
    const rootRef = useRef(null);
    const onClick = () => {
        const elements = rootRef.current;
        captureScreenshot(elements);
    };

    return (
        <div ref={rootRef}>
            <h2 style={{ color: "pink" }}>bla bla bla</h2>
            <button onClick={onClick}>ScreenShot</button>
        </div>
    );
}

ReactDOM.render(<App />, document.getElementById("root"));
Related