答案 0 :(得分:0)
是的,当然!要创建画布的剪辑,例如:
function getClip(x, y, width, height) {
var ocanvas = document.createElement('canvas'),
octx = ocanvas.getContext('2d');
ocanvas.width = width;
ocanvas.height = height;
octx.drawImage(mainCanvas, x, y, width, height // source rectangle
0, 0, width, height); // off-screen canvas
return ocanvas.toDataURL(); // return as data-uri
}
现在,您可以将data-uri作为锚标记的href,并设置下载属性:
<a download="myFilename.png" id="downloadLink">Click here to download</a>
并在JS中动态设置链接:
document.getElementById('downloadLink').href = getClip(x, y, w, h);
// optionally set file name 'download' here as well
这在大多数浏览器中运行良好,但在IE中却不行。但要利用可用的下载属性,您可以通过执行此操作来检查其支持:
function hasDownload() {
var a = document.createElement('a');
return (typeof a.download === 'string);
}
如果没有支持可能会为IE用户创建图像和下载说明的叠加层,或者在弹出窗口中显示图像等。
一个简单的例子:
var link = document.getElementById('downloadLink');
link.href = getClip(x, y, w, h);
if (!hasDownload) {
link.target = '_blank';
link.innerHTML = 'RIGHT-CLICK and chose "Save image as" to download.';
}