我在画布中有图像。
const canvas = document.createElement('canvas')
canvas.width = 640
canvas.height = 480
const context = canvas.getContext('2d')
element.appendChild(canvas)
const imageData = context.createImageData(640, 480)
imageData.data.set(new Uint8ClampedArray(data.frame))
context.putImageData(imageData, 0, 0)
我接收到数据(高度,宽度,x,y)。 我想根据此数据从画布上剪切图像并将其另存为blob文件。 我该怎么办?
答案 0 :(得分:0)
您的问题不清楚。该代码示例与问题描述不匹配。由于代码示例不起作用(未定义的变量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,但支持有限,因此,如果您知道目标是什么,请添加它。创建屏幕外画布剪切
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;
}
注意
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) }
}