Save canvas to image file

suggest change

You can save a canvas to an image file by using the method canvas.toDataURL(), that returns the data URI for the canvas’ image data.

The method can take two optional parameters canvas.toDataURL(type, encoderOptions): type is the image format (if omitted the default is image/png); encoderOptions is a number between 0 and 1 indicating image quality (default is 0.92).

Here we draw a canvas and attach the canvas’ data URI to the “Download to myImage.jpg” link.

HTML

<canvas id="canvas" width=240 height=240 style="background-color:#808080;">
</canvas>
<p></p>
<a id="download" download="myImage.jpg" href="" onclick="download_img(this);">Download to myImage.jpg</a>

Javascript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var ox = canvas.width / 2;
var oy = canvas.height / 2;
ctx.font = "42px serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#800";
ctx.fillRect(ox / 2, oy / 2, ox, oy);

download_img = function(el) {
  // get image URI from canvas object
  var imageURI = canvas.toDataURL("image/jpg");
  el.href = imageURI;
};

Live demo on JSfiddle.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents