关键代码
使用canvas的导出功能和drawImage函数
class CropShape{
cropShape(shape){
let {x,y,w,h} = shape
console.log(x,y,w,h)
const roiCanvas = document.createElement('canvas');
document.getElementById('app').append(roiCanvas)
const roiCtx = roiCanvas.getContext('2d');
roiCanvas.width = w;
roiCanvas.height = h;
roiCtx.drawImage(this.stage.image, x, y, w, h, 0, 0, w, h);
const dataURL = roiCanvas.toDataURL('image/png');
return dataURL;
}
downloadImage(dataURL, filename) {
const link = document.createElement('a');
link.href = dataURL;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
使用示例
let cimg = new CropShape()
let img = cimg.cropShape({
x:1,
y:1,
w:10,
h:10
})
cimg.downloadImage(cimg,'result.png')
绘制roi代码 demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Screenshot with ROI</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<input type="file" id="upload" accept="image/*">
<canvas id="canvas"></canvas>
<canvas id="roiCanvas" style="display:none;"></canvas>
<img id="croppedImage" alt="Cropped Image" />
<script>
const upload = document.getElementById('upload');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const roiCanvas = document.getElementById('roiCanvas');
const roiCtx = roiCanvas.getContext('2d');
const croppedImage = document.getElementById('croppedImage');
let image = new Image();
let startX, startY, endX, endY;
let isDrawing = false;
upload.addEventListener('change', function(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function(e) {
image.src = e.target.result;
};
reader.readAsDataURL(file);
});
image.onload = function() {
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0);
};
canvas.addEventListener('mousedown', function(event) {
startX = event.offsetX;
startY = event.offsetY;
isDrawing = true;
});
canvas.addEventListener('mousemove', function(event) {
if (isDrawing) {
endX = event.offsetX;
endY = event.offsetY;
draw();
}
});
canvas.addEventListener('mouseup', function(event) {
if (isDrawing) {
endX = event.offsetX;
endY = event.offsetY;
isDrawing = false;
cropImage();
}
});
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, 0, 0);
ctx.strokeStyle = 'red';
ctx.lineWidth = 2;
ctx.strokeRect(startX, startY, endX - startX, endY - startY);
}
function cropImage() {
const width = endX - startX;
const height = endY - startY;
roiCanvas.width = width;
roiCanvas.height = height;
roiCtx.drawImage(canvas, startX, startY, width, height, 0, 0, width, height);
const dataURL = roiCanvas.toDataURL();
croppedImage.src = dataURL;
croppedImage.style.display = 'block';
}
</script>
</body>
</html>
效果图
左下角为框选的roi区域里的图像内容