如何canvas.toBlob和canvas.toDataURL都无效,该用生命方法将canvas转为链接,请返回实现代码
时间: 2023-11-10 18:01:19 浏览: 238
以下是将 canvas 转为链接的示例代码:
```javascript
function canvasToLink(canvas, type, quality) {
return new Promise(resolve => {
canvas.toBlob(blob => {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = `canvas.${type}`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
resolve();
}, type, quality);
});
}
```
使用方法示例:
```javascript
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 100, 100);
canvasToLink(canvas, "png", 1);
```
此代码将生成一个红色的 100x100 像素的矩形,并将其转换为 png 图片,然后下载该图片。
阅读全文