Convert canvas to image
Jump to navigation
Jump to search
How to Convert & Download HTML5 Canvas as Image
Steps to convert HTML5 Canvas to Image[edit]
1. Visit any webpage containing HTML5 Canvas elements (Example: HTML Canvas tutorial on W3Schools)
2. Find canvas id in browser inspector:
<canvas id="myCanvas" width="270" height="160" style=" ... ">
Your browser does not support the canvas element.
</canvas>
In this example, the canvas element has an id of "myCanvas"
3. Open Developer Tools (e.g. Open Chrome DevTools on Chrome
)
3-1 Switch to Console
3-2 Paste this JavaScript code:
function downloadCanvas(canvasId, filename = 'canvas-image.png') {
const canvas = document.getElementById(canvasId);
const dataUrl = canvas.toDataURL();
const image = document.createElement('img');
image.src = dataUrl;
image.style.width = canvas.width + 'px';
image.style.height = canvas.height + 'px';
const downloadUrl = dataUrl.replace('image/png', 'application/octet-stream');
const link = document.createElement('a');
link.download = filename;
link.href = downloadUrl;
link.click();
return image;
}
3-2 Execute download function:
downloadCanvas('myCanvas', 'my-image.png');
Notes:
- Function name: Keep downloadCanvas unchanged unless you're comfortable with JavaScript
- Parameters:
- canvasId: Must match the canvas id in HTML (e.g. 'myCanvas')
- filename: Optional, customize the download filename