点击红球后移动到绿球位置
uni.createAnimation()使用代码如下
<template>
<view class="content">
<view :animation="animationA" class="topBox" @click="changeA()"></view>
<view class="bottomBox"></view>
</view>
</template>
<script setup lang="ts">
import { onShow } from '@dcloudio/uni-app'
import { getCurrentInstance, reactive, ref } from 'vue';
const that = getCurrentInstance()
let animation = reactive<any>({})
let topPosition = reactive<any>({})
let bottomPosition = reactive<any>({})
let animationA = ref<any>({})
onShow(()=>{
// 获取元素信息
uni.createSelectorQuery().in(that).select('.bottomBox').boundingClientRect(data => {
bottomPosition=data
}).exec()
uni.createSelectorQuery().in(that).select('.topBox').boundingClientRect(data => {
topPosition=data
}).exec()
// 初始化动画
animation = uni.createAnimation()
})
function changeA(){
//获取移动位置,并且转换成整数
let x =Math.round(bottomPosition.left - topPosition.left)
let y =Math.round(bottomPosition.top - topPosition.top)
animation.translateX(x).translateY(y).step({
// 执行动画移动过程所需时间
duration: 600,
})
animationA.value = animation.export()
// 加一个定时器定时给盒子元素复原
setTimeout(()=>{
animation.translateX(0).translateY(0).step({
// 执行动画移动过程所需时间
duration: 0,
})
animationA.value = animation.export()
},650)
}
</script>
<style scoped lang="scss">
.content {
height: 100vh;
display: flex;
.topBox {
height: 50rpx;
width: 50rpx;
border-radius: 50%;
background-color: red;
}
.bottomBox {
top: 800rpx;
left: 600rpx;
margin-top: auto;
margin-left: auto;
height: 50rpx;
width: 50rpx;
border-radius: 50%;
background-color: green;
}
}
</style>