vue图片放大镜功能代码实现
以下是Vue图片放大镜功能的代码实现:
- 创建一个Vue组件,命名为ImageZoom:
<template>
<div class="image-zoom">
<div class="image-zoom-container">
<img :src="source" @mousemove="zoomImage($event)">
</div>
</div>
</template>
<script>
export default {
props: {
source: { type: String, required: true },
zoomLevel: { type: Number, default: 2 }
},
data() {
return {
zoomed: false,
containerWidth: null,
containerHeight: null,
imageWidth: null,
imageHeight: null,
offsetX: null,
offsetY: null
};
},
methods: {
zoomImage(event) {
if (!this.zoomed) {
this.containerWidth = event.target.clientWidth;
this.containerHeight = event.target.clientHeight;
this.imageWidth = event.target.naturalWidth;
this.imageHeight = event.target.naturalHeight;
this.zoomed = true;
}
this.offsetX = event.offsetX;
this.offsetY = event.offsetY;
const x = (this.offsetX / this.containerWidth) * this.imageWidth;
const y = (this.offsetY / this.containerHeight) * this.imageHeight;
const zoomedImage = this.$el.querySelector(".zoomed-image");
zoomedImage.style.backgroundImage = `url(${this.source})`;
zoomedImage.style.backgroundSize =
this.imageWidth * this.zoomLevel + "px " + this.imageHeight * this.zoomLevel + "px";
zoomedImage.style.backgroundPosition =
-x * this.zoomLevel + "px " + -y * this.zoomLevel + "px";
}
}
};
</script>
<style scoped>
.image-zoom {
position: relative;
width: 100%;
height: 100%;
}
.image-zoom-container {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
}
.image-zoom-container img {
display: block;
width: 100%;
height: 100%;
}
.zoomed-image {
position: absolute;
top: 0;
left: 100%;
width: 100%;
height: 100%;
transform: scale(0.5);
transform-origin: left;
transition: transform 0.3s ease-out;
}
</style>
- 在父组件中使用ImageZoom组件,并传入图片路径和放大倍数:
<template>
<div class="parent-component">
<image-zoom :source="imagePath" :zoom-level="3" />
</div>
</template>
<script>
import ImageZoom from "@/components/ImageZoom.vue";
export default {
components: {
ImageZoom
},
data() {
return {
imagePath: "/path/to/image.jpg"
};
}
};
</script>
- 运行程序,鼠标移动到图片上即可看到放大效果。
原文地址: https://www.cveoy.top/t/topic/boWI 著作权归作者所有。请勿转载和采集!