前言
首先我们来解释一下什么叫环物设计,环物设计即利用切换图片(一个物体的各种角度)实现一种伪3D 的效果,多说无益,看下图:
是不是觉得贼炫酷,我要不说是不是给你感觉是用three.js 做的 3d 物品,嘿嘿 这就是我们的要的效果!
话不多说 上代码
在vue上实现环物设计
<template>
<div>
<div class="box">
<div
class="car"
id="car"
@mousedown="flag = true"
@mouseup="flag = false"
@mousemove="handelMousemove($event)"
></div>
</div>
</div>
</template>
<script>
import imgSrc1 from "@/assets/shoes/lue/img1.jpg";
import imgSrc2 from "@/assets/shoes/lue/img2.jpg";
import imgSrc3 from "@/assets/shoes/lue/img3.jpg";
import imgSrc4 from "@/assets/shoes/lue/img4.jpg";
import imgSrc5 from "@/assets/shoes/lue/img5.jpg";
import imgSrc6 from "@/assets/shoes/lue/img6.jpg";
import imgSrc7 from "@/assets/shoes/lue/img7.jpg";
import imgSrc8 from "@/assets/shoes/lue/img8.jpg";
export default {
data() {
return {
imgsArr: [
imgSrc1,
imgSrc2,
imgSrc3,
imgSrc4,
imgSrc5,
imgSrc6,
imgSrc7,
imgSrc8,
],
picNum: 1,
totalPicNum: 8, //图片的总个数
flag: false,
prePosition: 0,
nowPosition: 0,
car: null,
};
},
mounted() {
this.car = document.getElementById("car");
window.onmouseup = function () {
this.flag = false;
};
},
methods: {
handelMousemove(e) {
if (this.flag == true) {
console.log(e.pageX);
this.changePic(e.pageX - this.car.offsetLeft);
} else {
this.prePosition = e.pageX - this.car.offsetLeft;
}
},
changePic(nowPosition) {
if (this.prePosition - nowPosition > 25) {
//25为一个自定义的值,当鼠标移动距离大于25px时,切换图片
//切换图片之后,把当前位置赋值给上次的位置
this.prePosition = nowPosition;
//图片个数小于1的时候,变成最后一张图
this.picNum = --this.picNum < 1 ? this.totalPicNum : this.picNum;
this.car.style.backgroundImage = `url(${
this.imgsArr[this.picNum - 1]
})`;
} else if (this.prePosition - nowPosition < -25) {
this.prePosition = nowPosition;
//图片个数大于最后一张图的时候,变成第一张图
this.picNum = ++this.picNum > this.totalPicNum ? 1 : this.picNum;
this.car.style.backgroundImage = `url(${
this.imgsArr[this.picNum - 1]
})`;
}
},
},
};
</script>
<style>
* {
padding: 0;
margin: 0;
}
.car {
width: 700px;
height: 447px;
background-repeat: no-repeat;
background-image: url("../assets/shoes/lue/img1.jpg");
cursor: grab;
}
.car:active {
cursor: grabbing;
}
</style>
放在vscode 中看看
正好一百行! 是不是说明我这不是标题党 嘿嘿
注意事项
1、我们的思路就是用鼠标滑过 模拟一种拖拽的效果 然后动态切换背景图片
所以css 加的是cursor: grab; 当他被选中的是时候 cursor: grabbing;
2、要注意的是vue 中动态设置背景图片 用require 会有各种bug 导致显示不出来,最后实在没办法 只能将所有的图片导入放在一个数组中 动态切换数组
3、图片选择很重要 一定得选择角度均匀分割的图片 图片越多 转动的越丝滑