功能描述:
1.在vue2中实现截图粘贴功能且粘贴的图片宽高自适应容器设置的宽高,只允许在容器内粘贴一张图片,若容器内有图片,粘贴其他图片则自动替代新粘贴的图片.
2.清除容器内图片
3.粘贴的图片预览,且可通过鼠标滚轮缩放预览图
<template>
<div>
<div id="container" @paste="onPaste" style="width: 300px; height: 200px; border: 1px solid black;">
<input v-if="inputVal" style="height: 100%; width: 100%;" type="text">
<img :src="imageURL" v-if="imageURL" style="width: 100%; height: 100%; object-fit: cover;">
</div>
<button @click="clearImage">清除图片</button>
<button @click="openModal">预览原图</button>
<!-- 预览页面可鼠标滚轮缩放预览图片 -->
<div v-show="showModal" class="modal" @click="closeModal" @wheel="onMouseWheel">
<img :src="imageURL" v-if="imageURL" :style="{ transform: `scale(${scale})` }">
<button @click="closeModal">关闭</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
imageURL: null,
showModal: false,
scale: 1,
inputVal: true,
};
},
methods: {
// 监听粘贴事件
onPaste(e) {
this.inputVal = false
const items = (e.clipboardData || window.clipboardData).items;
let blob = null;
for (let i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') === 0) {
blob = items[i].getAsFile();
}
}
console.log(blob);
// 如果粘贴的内容不是图片
if (blob == null) {
alert('请先截图或复制图片')
return
}
// 如果粘贴的内容是图片
if (blob !== null) {
const reader = new FileReader();
reader.onload = (e) => {
// 更新图片URL
this.imageURL = e.target.result;
};
reader.readAsDataURL(blob);
}
},
clearImage() {
this.imageURL = null;
this.inputVal = true
},
openModal() {
this.showModal = true;
},
closeModal() {
this.showModal = false;
},
onMouseWheel(e) {
// 检测滚轮方向
const delta = Math.sign(e.deltaY);
// 根据滚轮方向调整缩放比例
if (delta > 0) {
this.scale -= 0.1;
} else if (delta < 0) {
this.scale += 0.1;
}
// 限制缩放比例的范围
if (this.scale < 0.1) {
this.scale = 0.1;
} else if (this.scale > 3) {
this.scale = 3;
}
}
}
};
</script>
<style>
.modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
}
.modal img {
max-width: 100%;
max-height: 100%;
transition: transform 0.3s ease;
}
.modal button {
position: absolute;
top: 10px;
right: 10px;
}
</style>