小程序使用this.animate实现3维动画切换

小程序使用this.animate实现3维动画切换

这里以三张图片为例

话不多说,直接上代码

wxml

javascript 复制代码
<view class="container">
	<view class="carousel" id="carousel_id">
		<view class="box" wx:for="{{items}}" wx:for-item="item" wx:for-index="index" wx:key="index" style="display: flex;flex-direction: column;transform: rotateY({{index * -120}}deg) translateZ({{translateZ}});">
			<image class="DoorLock" src="{{item.pic}}" />
		</view>
	</view>
</view>

<button type="primary" bindtap="play" style="margin-top: 200rpx;">切换</button>

js

javascript 复制代码
Page({
	data: {
    translateZ: '0px',
    rotateY: 0,
		items: [
			{ "name": "酒杏鲍菇", "pic": "https://api.jisuapi.com/recipe/upload/20160719/120829_70383.jpg" },
			{ "name": "醋黄瓜丝", "pic": "https://api.jisuapi.com/recipe/upload/20160719/120712_61817.jpg" },
			{ "name": "式柠檬蒸鲈鱼", "pic": "https://api.jisuapi.com/recipe/upload/20160719/115500_14721.jpg" },
		]
  },
  
	onLoad(options) {
		const that = this;
		wx.getSystemInfo({
			success: (res) => {
				that.setData({
					translateZ: (res.windowWidth / 2 - 20) + 'px'
				});
			}
    });
    console.log('translateZ的值为:' + this.data.translateZ)
	},

	play() {
    let that = this
		this.animate('#carousel_id', [
			{ ease: 'ease', rotateY: this.data.rotateY },
			{ ease: 'ease', rotateY: this.data.rotateY+120 }
		], 500, function () {
      let rotateY = that.data.rotateY + 120
      rotateY = rotateY == 360 ? 0 : rotateY
      that.setData({
        rotateY: rotateY
      })
      console.log('当前rotateY值为:' + that.data.rotateY)
		});
  },
});

wxss

javascript 复制代码
.container {
	margin: 20rpx 300rpx;
	width: 70px;
	height: 40px;
	position: relative;
	perspective: 1000px;
	-webkit-perspective: 1500px;
}

.carousel {
	width: 100%;
	height: 100%;
	position: absolute;
	transform-style: preserve-3d;
	-webkit-transform-style: preserve-3d;
	/* animation: rotation 10s infinite linear;
	-webkit-animation: rotation 10s infinite linear; */
}

.carousel:hover {
	animation-play-state: paused;
	-webkit-animation-play-state: paused;
}

.carousel view {
	display: block;
	position: absolute;
	width: 70px;
	height: 70px;
	/* left: 10px; */
	top: 10px;
	background: #2262E6;
	overflow: hidden;
	border: solid 2px #07C160;
}

.box image {
	filter: grayscale(0);
	cursor: pointer;
	transition: all 0.3s ease 0s;
	width: 100%;
	height: 100%;
}

.box image:hover {
	filter: grayscale(0);
	-webkit-filter: grayscale(0);
	transform: scale(1, 1);
	-webkit-transform: scale(1, 1);
}

@keyframes rotation {
	from {
		transform: rotateY(0deg);
	}

	to {
		transform: rotateY(360deg);
	}
}

.DoorLock {
  position: fixed;
  opacity: 0.9;
  height: 70px;
  width: 70px;
  /* margin-left: 80rpx; */
  margin-top: -40px;
  justify-content: center;
  /* background-color: greenyellow; */
}

说明

1.点击切换实现3维切换
2.每次点击旋转120度,也就是一圈的三分之一,并且每次会继承上次旋转的角度,不然再次点击时回复原位置
3.rotateY表示每个图片之间的位置角度,这里将三张图片按idnex均匀分布