先上效果图,该转盘可以根据商品数量生成与商品数量相等的等面积扇形,蓝线是指针
想看源码和效果直接看这里: code.juejin.cn/pen/7280812…
然后看不懂源码的或者想了解该转盘怎么实现的过程的,请看下面
- 首先在画圆之前,我们要先画一个扇形出来
实现代码如下:
<template>
<div class="sector"></div>
</template>
<style scoped>
.sector {
width: 100px;
height: 100px;
background: conic-gradient(red 90deg, transparent 0);
border-radius: 50%;
}
</style>
- 然后我们需要一个由多个扇形组成的圆,这个时候需要通过循环实现
实现代码如下:
<template>
<div>
<div v-for="(item,index) in list" class="sector" :key="index" :style="itemStyle(index)">{{item}}</div>
</div>
</template>
<script>
export default {
data() {
return {list:['商品1','商品2','商品3']}
},
methods:{
itemStyle(index){
let len=360/this.list.length
let rotate=len*index
return {
transform: `rotate(${rotate}deg)`,
background: `conic-gradient(red ${len-1}deg, transparent 0)`
}
}
}
}
</script>
<style scoped>
.sector {
width: 200px;
height: 200px;
position: absolute;
background: conic-gradient(red 180deg, transparent 0);
border-radius: 50%;
}
</style>
- 有了圆自然要开始想办法让它转起来了,所以要在循环外面加一个div,只要给这个div一个旋转的动画效果,这个转盘自然就转起来了
<template>
<div>
<div class="wheel" ref="wheel">
<div v-for="(item,index) in list" class="sector" :key="index" :style="itemStyle(index)">{{item}}</div>
</div>
<button @click="startRotation">开始旋转</button>
</div>
</template>
<script>
export default {
data() {
return {list:['商品1','商品2','商品3']}
},
methods:{
startRotation(){
this.$refs.wheel.style.transition = 'transform 5s ease-out';
this.$refs.wheel.style.transform = `rotate(1800deg)`;
},
itemStyle(index){
let len=360/this.list.length
let rotate=len*index
return {
transform: `rotate(${rotate}deg)`,
background: `conic-gradient(red ${len-1}deg, transparent 0)`
}
}
}
}
</script>
<style scoped>
.sector {
width: 200px;
height: 200px;
position: absolute;
background: conic-gradient(red 180deg, transparent 0);
border-radius: 50%;
}
.wheel {
width: 200px;
height: 200px;
transform-style: preserve-3d;
position: relative;
}
</style>
- 后面就是根据商品旋转选中商品的逻辑了,具体看源码。