tsayen / dom-to-image

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

Not rendering cloned Dom elements #236

Open erockdotdev opened 6 years ago

erockdotdev commented 6 years ago

Use case: description, code

Cloned DOM node will not render a png.

In this case var node = $btn.closest('.component-graph-container').find('.graph')[0]; node will render a png. in this case using .clone() let node = $btn.closest('.component-graph-container').clone(); will export a png but will be empty.

I'm not quite sure what is going on - it is necessary in my case to clone the original DOM element to make changes without mutating the original data. The clone will console.log with the expected dom elements.

I also tried creating a new element and appending the clone to that and passing that to domtoimage but had the same results as the clone iteself.

Expected behavior

Cloned DOM elements will render the same as original elements

Actual behavior (stack traces, console logs etc)

PNG is created but when opens alerts "[PNG] could not be opened because it is empty."

Library version

2.5.2

Browsers

nickswope commented 6 years ago

Here's a reproducible example: https://jsfiddle.net/x36a9oz2/6/

The first implementation works, the second does not. The only difference is the second one runs .cloneNode(true) on the node as it is passed into toPng

Looking at the source code, I don't understand why this is happening. cloneNode is used in a very similar way here, so I'm not sure why it doesn't work if the node is cloned prior to passing it in.

This also happens if you just try to create an element using document.createElement and pass that in. It's like the node has to be actually rendered into the DOM tree before this package works. Does anyone have an idea of why this is the case?

iamtekeste commented 5 years ago

I would love to hear a solution to this problem too.

MSCAU commented 4 years ago

Does anyone still need this sorted? I am cloning and rendering PNG successfully at https://beatjosh.com/budgets/FY2019/CTH (Click the SNAPSHOT button in the right toolbar.)

amit-sharechat commented 4 years ago

Facing the same issue ? Anyone able to figure it out ?

FA5I commented 4 years ago

I am having the same issue too - if cloned before passing in it does not render. Not sure why

AlexNecula commented 3 years ago

For my case, it seems that the width (it can also be height) was not specified in the cloned node. Therefore, the canvas created by the library had width 0 and when it was converted to URL it was empty. Specify the width and height when calling toPng.