Exporting & Saving
One thing that SVG can’t do is save the resulting image as a bitmap. It’s easy for <canvas> because the element is already a bitmap in the first place! The canvas can export its image to a data URL (e.g., data:image/png;base64,iVBORw0KGg...). This data may then be rendered in the browser, which could then be saved or dragged to the desktop, used in a new canvas, and so on.
The browser must support PNG images, and it may have varying support for GIF and JPG. For our example, we’ll stick with PNG since it supports alpha transparency, and where we haven’t drawn on the canvas, it’ll be transparent.
To get the data URL, we simply call canvas.toDataURL('image/png'). Note that we’re calling toDataURL() on the <canvas> element, not on the 2D context. This is because we’re getting all the pixels in the canvas, not just the pixels in a particular context.
So taking the example we’ve put together already, we’ll make the browser redirect to a PNG version of the image when a user clicks on the <canvas> element (a contrived example, I know!):
canvas.onclick = function () { window.location = canvas.toDataURL('image/png');};