Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Nils Garland
18,416 PointsSaving canvas as image jQuery
Hi, I just completed jQuery basics. I had so much fun building the drawing application so I tried to upgrade i a little bit. I wan't to be able to save the canvas that they draw on as an image. I thought "this must be super hard" but a quick search returned that it might not be as hard as I thought. I found some examples and tried to adapt them to my application. They did not work tho so I was hoping to get some help with it here in the community.
Here is my html:
<canvas width="600" height="400"></canvas> <!-- canvas -->
<button id="canvasImageSave">Save file!</button> <!-- Save button -->
Here is my jQuery code so far on downloading the file:
var $canvas = $("canvas"); // canvas var stored at the top of the code
var $link = $("#canvasImageSave");
$link.click(function(ev){
$link.href = $canvas.toDataURL();
$link.download = "mypainting.png";
}, false);
1 Answer
Steven Parker
243,318 Points
Hi, I got your request.
I'm not familiar with a ".saveAsPNG()" function, and all I could find in a search was a component of a commercial ($$) third-party document SDK.
I use Chrome, so I can save the drawing just by right-clicking and selecting "save image as". But if your browser doesn't offer saving from canvas, you could open it as an image in another window like this:
$("#newwindowbutton").click(function(){
var dataURL = $canvas[0].toDataURL('image/png');
var w = window.open('about:blank', 'image from canvas');
w.document.write("<img src='" + dataURL + "' alt='from canvas'/>");
});
Then, probably any browser will offer a "save as" option when you right-click on the new image window.