首推一个js插件,不会造轮子,还不会用轮子么...
npm install js-web-screen-shot@1.8.0
js-web-screen-shot
是一个基于 JavaScript 的屏幕截图工具,可以在网页中实现对当前页面或指定元素的截图操作。它通常使用 HTML5 中的Canvas API
和HTML DOM
技术创建画布并捕捉网页中的图像。
上代码
<template>
<div class='container'>
<button @click="btnclick">开始截屏</button>
<img src="https://img1.baidu.com/it/u=1859277775,4024083831&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1685811600&t=0adc40ae0c92c28df7d5bc102ea32b84" alt="">
</div>
</template>
<script>
import ScreenShort from 'js-web-screen-shot'
export default ({
data() {
return {
uploadlist: [],
imageFilelist: []
}
},
methods: {
btnclick() {
// 实例一个对象
const ScreenShortHandle = new ScreenShort({
enbleWebRtc: false,//是否显示选项的框
level: 99,//层级级别
completeCallback: this.callback,//完成截图的操作
closeCallback: this.closeFn,//自己操作即可
})
},
callback(base64data) {
var image = new Image()
image.src = base64data;
// 图片加载后触发回调
image.onload = () => {
var canvas = this.convertImageToCanvas(image);
var url = canvas.toDataURL("image/jpeg");
//
this.uploadlist.push({ image: url })
for (let i = 0; i < this.uploadlist.length; i++) {
if (this.uploadlist.length >= 6) {
this.uploadhide = false
}
}
console.log(this.uploadlist, "上传的图片列表")
//然后使用atob把图片解码
let bytes = window.atob(url.split(',')[1]);
//使用arrayBuffer存储数组中的二进制数据
let buffer = new ArrayBuffer(bytes.length)
let uint = new Uint8Array(buffer)//生成一个8位数的数组
for (let i = 0; i < uint.length; i++) {
uint[i] = bytes.charCodeAt(i);//根据长度返回相应的unicode编码
}
//Blob对象
var imageFile = new Blob([buffer], { type: "image/jpeg" })//type为图片格式
//给后台返回的数组,我们的需求是截图多张上传给后端,如果只是上传一张 ,就不用做imageFile这一行,后续可以围绕着这个。
this.imageFilelist.push(imageFile);
if (this.imageFilelist !== "") {
console.log("截图成功")
}
}
},
closeFn() {
},
// 使用canvas绘制一个复杂且交互性更强的图片
convertImageToCanvas(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0)
return canvas
}
},
computed: {},
mounted() { }
})
</script>
<style lang='scss' scoped>
.container {
width: 100%;
height: 100%;
}
</style>