Reputation: 43
I am currently working on a 2D, tile-based level editor game in HTML5. Right now I am allowing users to save their levels both on the browser using localStorage and download it, both as json strings. I want to be able to attach to the json an image of the level. I figured out how to create a copy of the level into a canvas and an image element for saving.
What I need now is a way to save the level out as png data so that I can attach my json string representation of the level, and then save it out as a png to the hard drive or store it in localStorage.
I have tried using canvas.toDataURL() but this only give me the canvas as a base64 encoded data and is not a png. I have tried canvas2image library but it will download the image before I can append the data.
So, to sum up, anyone know how to convert a canvas to a PNG file WITHOUT save as so I can attach some additional data to it before saving?
I am thinking this question is peaty straight forward so I am not adding any of my source code, particularly because it is in typescript.
Upvotes: 2
Views: 912
Reputation:
Can't be done. Period (not without modifying the browser's source code or making your own).
The toDataURL()
do give you a PNG (or JPEG if you specify it) but in the form of a data-uri. Its content is typically encoded as a Base64 string that needs to be decoded (which results in a binary PNG file).
Imagine the security risk if any web app could just save content to anywhere on the user's disk without their knowledge (cache, manifests, local storage excluded as there are isolated storage).
To save to localStorage
just save the Base64 string but be aware of the size limitations that is with localStorage
.
A base64 version is 33% larger in size than the original content and each char takes 2 bytes due to the Uni-coding so localStorage
may run fast out of space depending on the size of the images.
A better option is perhaps Indexed DB or even Web SQL (now deprecated) (there is File API too but currently only in Chrome) as you can request a size for these.
Upvotes: 2