export-canvas-as-image
Javascript Web Development

Export canvas as image with JavaScript

In previous tutorial, we talked about How to load image to canvas with JavaScript. This time we’ll show you how to export canvas as image and let user download it. Let’s check it out!

Let’s suppose that we have an image on our page and want to process it in canvas, then export it.

<img id="image1" src="image1.jpg" />

I’m going to reuse code from previous tutorial to load image to canvas.

let c = document.createElement("canvas");
ctx = c.getContext('2d');
let img1 = new Image();

//onload event listener to process the image data after it was loaded
img1.onload = function () {
  c.width = img1.width;
  c.height = img1.height;
  ctx.drawImage(img1, 0, 0);

  /* ready for canvas processing*/
};

//start loading image
img1.src = document.getElementById("image1").src;

export-canvas-as-image-1

Now the image is loaded to the canvas and ready for processing. Let’s put some red photo filter over the image before we export it

ctx.fillStyle = "rgba(100, 0, 0, 0.5)";
ctx.fillRect(0, 0, img1.width, img1.height);

Now if we want to export the image as DOM element, just use toDataURL method. Then attach it to something.

let img2 = new Image();
img2.src = c.toDataURL("image/jpeg");
document.body.appendChild(img2);

export-canvas-as-image-2

But if we want to export it as downloadable (popup the browser download window) things will be a bit more complicate as there is no universal cross browser solution. For example, we can use toBlob method with pseudo link element like so but that’s only work with Chrome.

//CHROME ONLY

let link = document.createElement("a");
link.download = "image.png";
c.toBlob(function(blob) {
  link.href = URL.createObjectURL(blob);
  link.click();
}, "image/png");

There are 2 major obstacles. First, toBlob is only supported in Firefox and Chrome. Second, we need to find a cross-browser solution to popup the file saving dialog.

Luckily, we have solutions for both. Canvas-toBlob.js is a polyfill that enable toBlob support for all browsers. And next is FileSaver.js which is a library for client-side file saving which is perfect for this job. Here is the browser support.

export-canvas-as-image-3

Now our job is much easier. Simply call saveAs method and pass our blob object, follow by a name for the image file.

<script src="FileSaver.min.js"></script>
<script src="canvas-toBlob.js"></script>

c.toBlob(function(blob){
   saveAs(blob, "myImage.png");
});

export-canvas-as-image-4

And that’s it. Here is the final source code for this project. Enjoy!! 🙂

Written By

Leave a Reply

Your email address will not be published. Required fields are marked *