qq15725 / modern-screenshot

📸 Quickly generate image from DOM node using HTML5 canvas and SVG
https://toolpkg.com/html-to-image
MIT License
504 stars 36 forks source link

Is there a way to use a non-rendered React component? #41

Closed pthieu closed 1 year ago

pthieu commented 1 year ago

I would like to take a list of data and render it in the background to generate images.

I have an array of data like this:

const data = [
  {
    height: 500,
    weight: 500,
    color: "#ff0000",
    text: "Hello World",
  },
  ...
];

I would like to loop through each item in the array and pass the data into a React element like:

for (const d of data) {
  const dataUrl = await domToBlob(<Component {...d} />);
  // upload to server
}

Is this possible?

qq15725 commented 1 year ago
const container = document.createElement('div')
container.style.opacity = '0'
container.style.position = 'fixed'
document.body.appendChild(container)

const root = document.createElement('div')
container.appendChild(root)

const reactRoot = ReactDOM.createRoot(root)
//              👇🏻
reactRoot.render(<div ref={ onDidMount }>Hello, world</div>)

function onDidMount() {
  modernScreenshot.domToPng(root).then(dataUrl => {
    const link = document.createElement('a')
    link.download = 'screenshot.png'
    link.href = dataUrl
    link.click()
  })
}

https://codepen.io/qq15725/pen/PoXYyBe

pthieu commented 1 year ago

thanks, had to modify slightly but this works migrating over to this library!