element和vue写一个放大镜功能
以下是一个基于Vue.js和Element UI的放大镜功能示例代码:
<template>
<div class="container">
<el-image
:src="imageSrc"
:style="{ width: '100%', height: 'auto' }"
@click.native="showMagnifier = true"
/>
<el-dialog
:visible.sync="showMagnifier"
:before-close="onBeforeClose"
custom-class="magnifier-dialog"
:center="true"
:close-on-click-modal="false"
>
<div class="magnifier-container">
<div class="magnifier-image" ref="magnifierImage">
<img :src="imageSrc" />
</div>
<div class="magnifier-glass" ref="magnifierGlass"></div>
</div>
</el-dialog>
</div>
</template>
<script>
export default {
data() {
return {
imageSrc: "https://picsum.photos/800/600",
showMagnifier: false,
magnifierWidth: 200,
magnifierHeight: 200,
magnifierRatio: 2,
magnifierImageWidth: 0,
magnifierImageHeight: 0,
magnifierGlassWidth: 0,
magnifierGlassHeight: 0,
magnifierGlassX: 0,
magnifierGlassY: 0,
};
},
mounted() {
this.magnifierImageWidth = this.$refs.magnifierImage.offsetWidth;
this.magnifierImageHeight = this.$refs.magnifierImage.offsetHeight;
this.magnifierGlassWidth = this.magnifierWidth / this.magnifierRatio;
this.magnifierGlassHeight = this.magnifierHeight / this.magnifierRatio;
},
methods: {
onBeforeClose(done) {
this.showMagnifier = false;
this.magnifierGlassX = 0;
this.magnifierGlassY = 0;
done();
},
onMouseMove(event) {
const magnifierContainer = this.$refs.magnifierImage.getBoundingClientRect();
const x = event.clientX - magnifierContainer.left - this.magnifierGlassWidth / 2;
const y = event.clientY - magnifierContainer.top - this.magnifierGlassHeight / 2;
this.magnifierGlassX = Math.min(Math.max(x, 0), this.magnifierImageWidth - this.magnifierGlassWidth);
this.magnifierGlassY = Math.min(Math.max(y, 0), this.magnifierImageHeight - this.magnifierGlassHeight);
},
},
};
</script>
<style scoped>
.container {
position: relative;
height: 600px;
overflow: hidden;
}
.el-image {
cursor: zoom-in;
}
.magnifier-dialog {
background-color: transparent;
box-shadow: none;
border: none;
margin: 0;
width: 100%;
height: 100%;
padding: 0;
overflow: hidden;
}
.magnifier-container {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
cursor: none;
}
.magnifier-image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
.magnifier-image img {
width: 100%;
height: 100%;
}
.magnifier-glass {
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
border-radius: 50%;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
transform: scale(2);
transform-origin: 0 0;
pointer-events: none;
}
</style>
这个组件包含一个el-image和一个el-dialog,点击el-image会显示el-dialog,在el-dialog内部创建了一个放大镜效果,通过鼠标移动来改变放大镜的位置和显示的图像部分。其中magnifierWidth和magnifierHeight表示放大镜的大小,magnifierRatio表示放大倍数,可以根据实际情况进行调整。magnifierGlass表示放大镜的位置,通过计算鼠标位置来更新其位置。
原文地址: https://www.cveoy.top/t/topic/bgIW 著作权归作者所有。请勿转载和采集!