微信小程序animation核心动画demo
微信小程序的核心动画可以通过 animation API 来实现。下面是一个简单的示例,展示了如何使用微信小程序的动画功能来创建一个基本的动画效果,比如让一个方块在屏幕上移动并缩放。
示例代码
1. index.wxml
<view class="container">
<view class="box" animation="{{animation}}" bindtap="startAnimation"></view>
</view>
2. index.js
Page({ data: { animation: {} }, startAnimation: function () { // 创建动画实例 const animation = wx.createAnimation({ duration: 1000, // 动画持续时间 timingFunction: 'ease', // 动画的速度曲线 }); // 定义动画效果 animation.translateX(100).scale(1.5).step(); // 向右移动100px,并放大1.5倍 animation.rotate(45).step(); // 旋转45度 animation.opacity(0.5).step(); // 改变透明度到0.5 // 更新动画数据 this.setData({ animation: animation.export() // 导出动画数据 }); } });
3. index.wxss
.container { display: flex; justify-content: center; align-items: center; height: 100vh; /* 设置容器高度为视口高度 */ } .box { width: 100px; height: 100px; background-color: #3498db; /* 蓝色方块 */ border-radius: 10px; /* 圆角 */ }
代码说明
-
HTML 部分:
- 创建一个
<view>作为容器,里面放置一个带动画的box元素。 - 为
box绑定了一个tap事件,点击时触发startAnimation方法。
- 创建一个
-
JavaScript 部分:
- 在
data中定义一个animation属性,用于存储动画数据。 startAnimation方法创建动画实例,定义动画效果(移动、缩放、旋转和透明度变化)。- 使用
translateX方法使方块向右移动100px,scale方法放大1.5倍,rotate方法旋转45度,以及opacity方法设置透明度为0.5。 - 使用
step方法表示动画的一个步骤,最后用export导出动画数据并更新到data中。
- 在
-
CSS 部分:
- 设置容器的样式,使其居中显示。
- 定义方块的样式,包括大小、颜色和圆角效果。
运行效果
点击蓝色方块后,方块将向右移动 100 像素、放大 1.5 倍、旋转 45 度并变为半透明。这个简单的示例展示了如何使用微信小程序的核心动画 API 创建基本动画效果。
如果您想要更复杂的动画或有其他问题,请随时询问!
浙公网安备 33010602011771号