vue 实现截屏功能
使用html2canvas库实现截屏
在Vue项目中安装html2canvas库
npm install html2canvas --save
引入html2canvas并创建截图方法
import html2canvas from 'html2canvas';
methods: {
captureScreenshot() {
html2canvas(document.querySelector("#capture-area")).then(canvas => {
const link = document.createElement('a');
link.download = 'screenshot.png';
link.href = canvas.toDataURL('image/png');
link.click();
});
}
}
使用vue-html2canvas插件
安装vue-html2canvas插件
npm install vue-html2canvas
在组件中使用指令
import VueHtml2Canvas from 'vue-html2canvas';
Vue.use(VueHtml2Canvas);
methods: {
takeScreenshot() {
this.$html2canvas(this.$refs.screenshotElement, {
backgroundColor: null,
logging: false
}).then(canvas => {
canvas.toBlob(blob => {
saveAs(blob, 'screenshot.png');
});
});
}
}
实现区域选择截图
创建选择区域截图功能
data() {
return {
isSelecting: false,
startX: 0,
startY: 0,
width: 0,
height: 0
};
},
methods: {
startSelection(e) {
this.isSelecting = true;
this.startX = e.clientX;
this.startY = e.clientY;
},
duringSelection(e) {
if (this.isSelecting) {
this.width = e.clientX - this.startX;
this.height = e.clientY - this.startY;
}
},
endSelection() {
this.isSelecting = false;
if (this.width > 10 && this.height > 10) {
this.captureSelectedArea();
}
}
}
使用Canvas API实现高级截图
创建自定义截图方法
methods: {
customCapture() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const target = this.$refs.targetElement;
canvas.width = target.offsetWidth;
canvas.height = target.offsetHeight;
ctx.drawImage(target, 0, 0, canvas.width, canvas.height);
// 添加水印
ctx.font = '20px Arial';
ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
ctx.fillText('Watermark', 10, 30);
canvas.toBlob(blob => {
const url = URL.createObjectURL(blob);
window.open(url);
}, 'image/png');
}
}
实现全屏截图
创建全屏截图方法
methods: {
captureFullPage() {
html2canvas(document.body, {
scrollY: -window.scrollY,
scrollX: -window.scrollX,
windowWidth: document.documentElement.scrollWidth,
windowHeight: document.documentElement.scrollHeight
}).then(canvas => {
document.body.appendChild(canvas);
});
}
}
截图后的处理选项
添加截图后处理功能
methods: {
processScreenshot(canvas) {
// 转换为Blob
canvas.toBlob(blob => {
// 上传到服务器
const formData = new FormData();
formData.append('screenshot', blob);
axios.post('/api/upload', formData)
.then(response => {
console.log('Upload successful');
});
});
// 或者转换为Base64
const base64 = canvas.toDataURL('image/jpeg', 0.8);
this.$emit('screenshot-taken', base64);
}
}






