How to save an image from canvas.
A Pen by Jose Luis Quintana on CodePen.
How to save an image from canvas.
A Pen by Jose Luis Quintana on CodePen.
| <h1>Download Canvas</h1> | |
| <div id="container"> | |
| <canvas id="canvas" width="200" height="200"></canvas> | |
| <button id="btndownload">Download</button> | |
| </div> |
| // Initializing | |
| window.onload = function(){ | |
| var dwn = document.getElementById('btndownload'), | |
| canvas = document.getElementById('canvas'), | |
| context = canvas.getContext('2d'); | |
| // Drawing a circle | |
| var centerX = canvas.width / 2; | |
| var centerY = canvas.height / 2; | |
| var radius = 70; | |
| context.beginPath(); | |
| context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false); | |
| context.fillStyle = 'rgba(0,200,0, .7)'; | |
| context.fill(); | |
| context.lineWidth = 2; | |
| context.strokeStyle = 'black'; | |
| context.stroke(); | |
| // Drawing a rect | |
| context.beginPath(); | |
| context.rect(10, 50, 100, 100); | |
| context.fillStyle = 'rgba(255,255,0, .7)'; | |
| context.fill(); | |
| context.lineWidth = 2; | |
| context.strokeStyle = 'black'; | |
| context.stroke(); | |
| // Event handler for download | |
| dwn.onclick = function(){ | |
| download(canvas, 'myimage.png'); | |
| } | |
| } | |
| // Source from: http://stackoverflow.com/questions/18480474/how-to-save-an-image-from-canvas | |
| /* Canvas Donwload */ | |
| function download(canvas, filename) { | |
| /// create an "off-screen" anchor tag | |
| var lnk = document.createElement('a'), | |
| e; | |
| /// the key here is to set the download attribute of the a tag | |
| lnk.download = filename; | |
| /// convert canvas content to data-uri for link. When download | |
| /// attribute is set the content pointed to by link will be | |
| /// pushed as "download" in HTML5 capable browsers | |
| lnk.href = canvas.toDataURL("image/png;base64"); | |
| /// create a "fake" click-event to trigger the download | |
| if (document.createEvent) { | |
| e = document.createEvent("MouseEvents"); | |
| e.initMouseEvent("click", true, true, window, | |
| 0, 0, 0, 0, 0, false, false, false, | |
| false, 0, null); | |
| lnk.dispatchEvent(e); | |
| } else if (lnk.fireEvent) { | |
| lnk.fireEvent("onclick"); | |
| } | |
| } |
| h1 { | |
| text-align: center; | |
| } | |
| #container { | |
| width: 200px; | |
| height: 200px; | |
| margin: 0 auto; | |
| text-align: center; | |
| } | |
| #canvas { | |
| border: solid 1px gray; | |
| margin-bottom: 10px; | |
| display: block; | |
| } |