exupero / saveSvgAsPng

Save SVGs as PNGs from the browser.
MIT License
1.09k stars 362 forks source link

saveSvgAsPng.js:222 Uncaught TypeError: Cannot set property 'prepareSvg' of undefined #176

Closed FlorianLeitgeb closed 6 years ago

FlorianLeitgeb commented 6 years ago

I have downloaded the project and built a es2015 js file and included it with a script tag to my page. When I load the page, following error is shown in the console: saveSvgAsPng.js:222 Uncaught TypeError: Cannot set property 'prepareSvg' of undefined

And when I try to use the function saveSvgAsPng(), I get a ReferenceError: Uncaught ReferenceError: saveSvgAsPng is not defined

Here is the code of my usage: function exportToPNG() { saveSvgAsPng(document.getElementsByTagName("svg")[0], "diagram.png"); }

FlorianLeitgeb commented 6 years ago

I had to add an array accessor "[0]" to the svg object in line 37, 39, 48, 49, 91 and 92 to get it work. But now I only get a black rectangle.

exupero commented 6 years ago

Based on the error messages you report, I'd say the following line is returning undefined for some reason:

https://github.com/exupero/saveSvgAsPng/blob/ff408c983b27091f3de2b6fa05bac214df58266f/src/saveSvgAsPng.js#L2

That seems very unusual. this should be window if the library is included as a script tag.

Also, I don't understand the line numbers you gave. What file? They don't seem to have any relevance to your comment in the main script file.

shrickus commented 6 years ago

I'm seeing the same thing -- because this is actually undefined, not a reference to the window object as expected...

FWIW, the way I'm including your library is by appending this element:

<script src="vendor/save-svg-as-png/lib/saveSvgAsPng.js"></script>

at the end of my html page, inside the <body>...</body> tags. So the file is local to the same web server, and the file contents are properly being returned with the correct content-type. Hope this helps.

shrickus commented 6 years ago

Florian,

Until this is sorted out, you can modify the second line to include || window; at the end -- since that is what this is supposed to point to anyway...

exupero commented 6 years ago

Thanks for the confirmation. Looks like when the ES6 code is used, this is window, but when the ES5 code is used, this is undefined. I've added window as a fallback and published v1.4.5. Let me know if you have any further problems.