js将canvas保存成图片并下载
时间: 2024-10-14 13:15:49 浏览: 45
js 将canvas生成图片保存,或直接保存一张图片的实现方法
在JavaScript中,你可以使用HTML5 Canvas API结合Blob和URL.createObjectURL技术来把Canvas内容转换为图片,并提供给用户下载。以下是简单的步骤:
1. 创建一个HTML `<a>`标签用于触发下载操作:
```html
<a id="downloadLink" style="display:none;"></a>
```
2. 定义一个函数,比如`saveCanvasAsImage`,来创建Blob并生成下载链接:
```javascript
function saveCanvasAsImage(canvas, filename) {
var imgData = canvas.toDataURL('image/png');
var blob = atob(imgData.substring(imgData.indexOf(',')+1));
var arrayBuffer = new Uint8Array(blob.length);
for (var i = 0; i < blob.length; i++) {
arrayBuffer[i] = blob.charCodeAt(i);
}
var urlObject = window.URL.createObjectURL(new Blob([arrayBuffer], {type: 'image/png'}));
var link = document.getElementById('downloadLink');
link.href = urlObject;
link.download = filename;
link.style.display = 'block';
link.click();
// 清理临时URL
setTimeout(function() {
window.URL.revokeObjectURL(urlObject);
link.remove();
}, 0); // 立即释放资源,防止内存泄漏
}
```
3. 调用这个函数时,传入Canvas元素和你想要的文件名:
```javascript
var canvas = document.getElementById('myCanvas'); // 替换为实际canvas的id
saveCanvasAsImage(canvas, 'myCanvas.png');
```
阅读全文