你的问题不清楚。代码示例与问题描述不匹配。由于代码示例不起作用(未定义变量data),我只能按照问题的描述进行。
我收到数据(高度、宽度、x、y)。我想根据这些数据从画布上剪切一个图像并将其保存为 blob 文件。我该怎么做?
从图像中剪切
从画布上剪切一个矩形区域
function cutArea(fromImage, x, y, width, height) {
const cut = document.createElement("canvas");
cut.width = width;
cut.height = height;
const ctx = cut.getContext("2d");
ctx.drawImage(fromImage, -x, -y);
return cut;
}
您应该使用 offscreenCanvas,但支持有限,因此如果您知道您的目标是什么,请添加它。创建一个offscreenCanvas剪切
function cutArea(fromImage, x, y, width, height) {
const cut = new OffscreenCanvas(width, height);
const ctx = cut.getContext("2d");
ctx.drawImage(fromImage, -x, -y);
return cut;
}
注意
- 像素比例未更改且没有边界检查。如果坐标不在图像源上,部分或全部剪切图像可能为空(0 alpha)。
-
fromImage 可以是任何有效的图像源,包括画布。
-
width 和 height 必须 > 0 否则函数会抛出错误。
下载
将剪辑下载到本地存储作为下载的“image/png”图像文件。注意文件名可以由用户在下载时更改。图像类型是默认的png。没有办法知道下载是否成功。
function downloadCut(cut, name) {
const a = document.createElement("a");
a.download = name + ".png";
const download = blob => {
const url = a.href = URL.createObjectURL(blob);
a.dispatchEvent(new MouseEvent("click", {view: window, bubbles: true, cancelable: true}));
setTimeout(() => URL.revokeObjectURL(url), 1000); // clean up
}
if (cut instanceof OffscreenCanvas) { cut.convertToBlob().then(download) }
else { canvas.toBlob(download) }
}