mindo mindo -4 years ago 137
Javascript Question

Save only a certain part of an HTML canvas

Is it possible to save or export only a certain part of the canvas rather than the whole canvas?


At the moment, when I save the file I get the composition plus the transparent background (light blue in example above) of the entire canvas element I have on the site. What I would like to get is only the gray region (which could be made up of several images and text elements).

Answer Source

Yes you can, yet while I was making the JSFiddle, Michael Laszlo beat me to the punch. Either way, I put some time into this, so I'm still posting my answer.

First, you need to take a clipping of the image in your canvas. This is pretty simple. I made another canvas (a hidden one) and used the context.drawImage

var hidden_ctx = hidden_canvas.getContext('2d');


Now, we need the Data URL from this canvas so we can download the contents. For this, we will use the canvas.toDataURL method.

var data_url = hidden_canv.toDataURL("image/png").replace("image/png", "image/octet-stream");

Now, all we need to do is make a download link (an a element with an href attribute of our data_url) and we're done!

Thanks guys, and I'm sorry I wasn't fast enough to get the worm on this one, which makes me very sad. At least my JSFiddle should be helpful.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download