My use case is: I have a web site editor and a list of available web pages for users. Each page in this list is represented by a thumbnail. Every time a user makes a change to a page using the editor, the thumbnail of the respective site has to be updated to reflect the change. The way I'm doing is by mounting a ThumbnailSandbox component in the page, passing the props from the Redux store and then using dom-to-png to create the screenshot and use it in the list. But I wanted to do it without mounting the component on the page, because I think it would be a cleaner solution and with less chances of being affected by other interactions happening. So, I created a CodeSanbox to illustrate what I'm trying to achieve.
My logic is this:
import React from "react";
import ReactDOMServer from "react-dom/server";
import html2canvas from "html2canvas";
import MyComp from "./component.jsx";
export const createScrenshot = () => {
const el = (
<div>
test component <MyComp />
</div>
);
const markup = ReactDOMServer.renderToString(el);
let doc = new DOMParser().parseFromString(markup, "text/html");
let target = doc.body.getElementsByClassName("my-comp")[0];
console.log(markup, target);
html2canvas(target, {
useCORS: true,
allowTaint: true,
scale: 1,
width: 500,
height: 500,
x: 0,
y: 0,
logging: true,
windowWidth: 500,
windowHeight: 500
})
.then(function(canvas) {
console.log(">> ", canvas);
})
.catch(error => {
console.log(error);
});
};
So, I'm passing the component to ReactDOM, then creating a DOM node using the string from first step and passing the node to html2canvas. But at this point I get the error Uncaught TypeError: Cannot read property 'pageXOffset' of null
. Because the ownerDocument of the element passed to html2canvas is null and it doesn't have the properties: devicePixelRation, innerWidth, innerHeight, pageYOffset, and pageXOffset. As I understand, that's because the node element is not part of the DOM.
Now, my questions are:
1) Is there a way to solve this problem using html2canvas?
2) Is there any other way to take a screenshot of a React component, in the browser, without mounting the component in the DOM?
Thank you in advance!!