tsayen / dom-to-image

Generates an image from a DOM node using HTML5 canvas
Other
10.31k stars 1.69k forks source link

Doesn't work with JS element #208

Open grantlonie opened 6 years ago

grantlonie commented 6 years ago

Library works really great! Creates really accurate images of my dom structure. However, I would like to create an image without having to actually render it. Meaning I created an element with JS document.createElement and stuffed a bunch of html content in it using react, but the image would only generate if I first appended the element to the DOM. I'm hoping to prevent having to do this, because I think it will speed up the image creation process.

Here is some simplified code that works by appending the image to the document.

const domNode = document.createElement('div')
const newContent = document.createTextNode('Hi there and greetings!')
domNode.appendChild(newContent)
document.body.appendChild(domNode)
domtoimage
    .toPng(domNode, { quality: 0.1 })
    .then(dataUrl => {
        const img = new Image()
        img.src = dataUrl
        console.log(dataUrl)
        document.body.appendChild(img)
    })
    .catch(function(error) {
        console.error('oops, something went wrong!', error)
    })

But if I don't append the domNode to the dom as follows (same code just commented out where the node is appended to the dom):

const domNode = document.createElement('div')
const newContent = document.createTextNode('Hi there and greetings!')
domNode.appendChild(newContent)
// document.body.appendChild(domNode)
domtoimage
    .toPng(domNode, { quality: 0.1 })
    .then(dataUrl => {
        const img = new Image()
        img.src = dataUrl
        console.log(dataUrl)
        document.body.appendChild(img)
    })
    .catch(function(error) {
        console.error('oops, something went wrong!', error)
    })

It doesn't work. The console.log returns 'data:,', so the image isn't created.

Is there some reason that the html has to be tied to the dom?

Symyon commented 6 years ago

I am trying to solve a similar issue. I a have a React element I want to render when it un-mounts. I am saving the DOM node, but it refuses to render if the actual component is not rendered by the browser.

goroya commented 1 year ago

me too