Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
861 views
in Technique[技术] by (71.8m points)

reactjs - Element is not attached to a document html2canvas

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);
 });
question from:https://stackoverflow.com/questions/65601852/element-is-not-attached-to-a-document-html2canvas

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...