<template>
<div>
<canvas ref="canvas"></canvas>
<button @click="takeScreenshot">截图</button>
</div>
</template>
<script>
export default {
data() {
return {
originalImage: null,
comparisonImage: null,
};
},
mounted() {
this.loadImages();
},
methods: {
loadImages() {
// 加载原图和对比图
this.originalImage = new Image();
this.comparisonImage = new Image();
this.originalImage.src = 'path/to/original/image.jpg';
this.comparisonImage.src = 'path/to/comparison/image.jpg';
this.originalImage.onload = () => {
this.drawImage(this.originalImage, 0, 0);
};
this.comparisonImage.onload = () => {
this.drawImage(this.comparisonImage, this.originalImage.width, 0);
};
},
drawImage(image, x, y) {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
ctx.drawImage(image, x, y);
},
takeScreenshot() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
const x = 100; // 截图起始x坐标
const y = 100; // 截图起始y坐标
const width = 200; // 截图宽度
const height = 200; // 截图高度
// 创建一个新的Canvas用于截图
const screenshotCanvas = document.createElement('canvas');
screenshotCanvas.width = width;
screenshotCanvas.height = height;
// 将截图区域绘制到新的Canvas上
const screenshotCtx = screenshotCanvas.getContext('2d');
screenshotCtx.drawImage(canvas, x, y, width, height, 0, 0, width, height);
// 保存截图
const dataURL = screenshotCanvas.toDataURL('image/png');
this.downloadImage(dataURL);
},
downloadImage(dataURL) {
const link = document.createElement('a');
link.download = 'screenshot.png';
link.href = dataURL;
link.click();
}
}
};
</script>
<style>
/* 样式可以根据需要添加 */
</style>
前端截图并保存
于 2024-07-05 11:57:04 首次发布