商城系統(tǒng) 注冊(cè)

小程序購物車拋物線動(dòng)畫的實(shí)現(xiàn)

2020-09-27|HiShop
導(dǎo)讀:小程序購物車拋物線動(dòng)畫的實(shí)現(xiàn),要如何開發(fā),下面為大家介紹這篇文章。...

小程序購物車拋物線動(dòng)畫的實(shí)現(xiàn),要如何開發(fā),下面為大家介紹這篇文章。

小程序購物車拋物線動(dòng)畫的實(shí)現(xiàn)

 

分析

要實(shí)現(xiàn)拋物線動(dòng)畫,我當(dāng)時(shí)想到的是用插件的方式,網(wǎng)上有很多,但是要兼容小程序還是有點(diǎn)困難,況且小程序的主包有2M限制;

那么如何在小程序中實(shí)現(xiàn)這種效果呢?

 wx.createAnimation 
css3 transition

實(shí)現(xiàn)方式有了,我們?cè)賮砜匆幌率裁词菕佄锞€,數(shù)學(xué)上定義拋物線的種類有很多,但就上圖的效果而言,需要 水平方向勻速運(yùn)動(dòng) & 垂直方向加速運(yùn)動(dòng) ; wx.createAnimation 提供 timingFunction , 即水平方向 linear , 垂直方向 ease-in

小程序?qū)崿F(xiàn)

本次實(shí)現(xiàn)基于 wepy框架 (非小程序原生),所以 $apply ---> setData 就好了~

html

<view class="box">
	<view>
        <button bindtap="handleClick">點(diǎn)擊</button>
    </view>
    <view animation="{{animationY}}" style="position:fixed;top:{{ballY}}px;" hidden="{{!showBall}}">
        <view class="ball" animation="{{animationX}}" style="position:fixed;left:{{ballX}}px;"></view>
    </view>
</view>

JS

// 設(shè)置延遲時(shí)間
    methods = {
		handleClick: (e) => {
			// x, y表示手指點(diǎn)擊橫縱坐標(biāo), 即小球的起始坐標(biāo)
			let ballX = e.detail.x,
			    ballY = e.detail.y;
			this.isLoading = true;
			this.$apply();
			this.createAnimation(ballX, ballY);
		}
    }
	setDelayTime(sec) {
		return new Promise((resolve, reject) => {
			setTimeout(() => {resolve()}, sec)
		});
	}
	// 創(chuàng)建動(dòng)畫
	createAnimation(ballX, ballY) {
		let that = this,
		bottomX = that.$parent.globalData.windowWidth,
		bottomY = that.$parent.globalData.windowHeight-50,
		animationX = that.flyX(bottomX, ballX),      // 創(chuàng)建小球水平動(dòng)畫
		animationY = that.flyY(bottomY, ballY);			 // 創(chuàng)建小球垂直動(dòng)畫

		that.ballX = ballX;
		that.ballY = ballY;
		that.showBall = true;
		that.$apply();
		that.setDelayTime(100).then(() => {
			// 100ms延時(shí),  確保小球已經(jīng)顯示
			that.animationX = animationX.export();
			that.animationY = animationY.export();
			that.$apply();
			// 400ms延時(shí), 即小球的拋物線時(shí)長(zhǎng)
			return that.setDelayTime(400);
		}).then(() => {
			that.animationX = this.flyX(0, 0, 0).export();
			that.animationY = this.flyY(0, 0, 0).export();
			that.showBall = false;
			that.isLoading = false;
			that.$apply();
		})
	}
	// 水平動(dòng)畫
	flyX(bottomX, ballX, duration) {
		let animation = wx.createAnimation({
			duration: duration || 400,
			timingFunction: 'linear',
		})
		animation.translateX(bottomX-ballX).step();
		return animation;
	}
	// 垂直動(dòng)畫
	flyY(bottomY, ballY, duration) {
		let animation = wx.createAnimation({
			duration: duration || 400,
			timingFunction: 'ease-in',
		})
		animation.translateY(bottomY-ballY).step();
		return animation;
	}

小程序購物車拋物線動(dòng)畫的實(shí)現(xiàn)

電話咨詢 預(yù)約演示 0元開店