I am trying to convert an HTML5 canvas to an image. This is what I got so far:

but the problem is that I get this code:

I want a normal image path that the user can download!

Any help?

Test TestTest Test

4 Answers

Info: IE10+ doesn't support below method at all. Other people already did the work and implemented cross browser solutions. This is one of them.

First, add the generated data URL to the href attribute of an <a> tag.However on some browsers, this alone will not trigger a download. Instead it will open the linked image in a new page.

Download dialog for a base64 image:

Based on above example, convert the MIME type of the data URL to this:

By telling the browser that the data are application/octet-stream, it will ask you to save it on your hard-disk.

Specifying a filename:

As Adi said in the comments below, there is no standard way to define a filename using this method. But, there are two approaches which might work in some browsers.

A) The download attribute introduced by Google Crome

B) Defining HTTP headers within the data URL
headers=Content-Disposition: attachment; filename=image.png

This worked at least in some older versions of Opera. Here is some discussion about this.

Looking into the Bug/Feature-Tracking systems of the major browsers shows that defining a filename is quite a big wish of the community. Maybe we will see a cross-browser compatible solution in near future! ;)

Save RAM and CPU ressources:

If you don't want to bloat the RAM of your visitor's browser, you can also generate the data URL dynamically:

This way, your canvas may still be shown as an image file by your browser.If you want to increase the probability to open a download dialog, you should extend the function above, so that it does the replacement as shown above:

Last, add the HTTP header to make extra sure that most browsers offer a valid filename to you! ;)

FULL EXAMPLE:
Community
NippeyNippey

You can use the reimg library to convert the canvas to an image object, and even trigger the download for the user.

After you insert the library in your page, just use this :ReImg.fromCanvas(yourCanvasElement).downloadPng()

gillybgillyb

You have 2 options (both work on almost all browsers):

1- POST the data to the server:
On the server you'd have a script that will handle the data and then tell the browser to prompt the user for download.

2- Prompt the user for download usingDownloadify

AdiAdi

You might also consider using Concrete.js http://www.concretejs.com, which is a light weight HTML5 Canvas framework that enables peripheral things like this, including downloads. You would just do this:

and you're done.

Eric RowellEric Rowell

Not the answer you're looking for? Browse other questions tagged javascripthtml5canvas or ask your own question.