在进入APP时,通常都会有一个欢迎界面,用于展示APP的名称、logo,并预先加载部分数据。既然是欢迎页面,自然少不了一些动画元素。简单运用了CSS3和JS的动画效果,progress组件以及倒计时撸了一个欢迎页面。直接上效果:
1、基于CSS3的动画效果
1.1 给动画元素设置animation属性。
- animation-name:动画名
- animation-duration:动画持续时间
- animation-delay:动画开始前延迟时间
- animation-iteration-count:动画重复次数
- animation-timing-function:动画执行速度
- animation-fill-mode:动画模式
<image src="/common/huaWei.jpeg" class="logo"></image>
.logo {
width: 300px;
height: 300px;
border-radius: 150px;
animation-name: an1;
animation-duration: 5s;
animation-iteration-count: 1;
animation-timing-function: linear;
animation-fill-mode: none;
}
1.2 用"@keyframes 动画名"匹配设置动画规则。
@keyframes an1 {
from {
transform: rotate(180deg);
opacity: 0.3;
}
to {
transform: rotate(360deg);
opacity: 1.0;
}
}
除from,to外,还可以使用百分比(如20%{...})方式设置动画途中的效果。
以上两步,就实现了gif图中HUAWEI的logo旋转和逐渐清晰的动画效果。
2、基于JS的动画效果
2.1 动画元素给定id/ref等可以用于元素匹配的属性。
<image src="/common/liteMall.png" class="textImg" id="textImg"></image>
2.2 在onShow()方法中获取元素实例,并用animate()方法给定动画规则和基本属性。注意这一步在onInit()和onReady()中执行是没有效果的。
animate()接受两个参数,第一个为数组,指定动画的关键帧效果。第二个为对象,指定动画的基本属性。
2.3 调用play()方法开始动画执行。
onShow() {
// 设置动画
let textImg = this.$element("textImg").animate([
{
transform: {translateY: '200px'}, opacity: 0.1
},
{
transform: {translateY: '0px'}, opacity: 1
}
], {
duration: 5000,
easing: "linear-out-slow-in",
fill: "forwards",
iterations: 1
});
textImg.play();
}
这个方法在开发者文档中未找到说明,但证实可用,且IDE也是有提示的。


transform其中的key输入却是没有提示了。

这里写完后会有红线说缺少属性,但运行是没问题的,可以忽略。如果看着难受可以把数组单独声明为一个变量,再作为animate()方法入参。
以上三步,就实现了gif图中"litemall"字样从下方上移并逐渐清晰的动画效果。
对比CSS3的动画技术,使用JS实现动画会更有灵活性。可以在onShow()中定义动画,在用户进行一定操作后再执行。CSS3的只能在页面显示后一定时间执行,但可以用百分比的形式定义更丰富的动画渐变效果。
3、JS定时器
setTimeout()和setInterval()两个定时函数在鸿蒙中可以无缝对接使用。
gif图中的倒计时使用setInterval()实现每1秒倒数一个数并改变省略号的个数,在倒数到0时清除定时器。为防止僵尸线程影响性能,切记调用clearTimeout()和clearInterval()清除掉定时器。
倒计时部分,hml视图层:
<div class="loading">
<progress type="circular"></progress>
<text>
{{ loading }}
</text>
</div>
<text class="count">
{{ seconds }}
</text>
css渲染层:
.loading {
width: 100%;
height: 150px;
display: flex;
justify-content: center;
align-items: center;
}
progress {
width: 120px;
height: 120px;
}
.loading>text {
font-size: 40px;
color: #666666;
}
.count {
position: fixed;
bottom: 385px;
left: 225px;
font-size: 60px;
color: #666666;
}
js逻辑层:
onShow() {
// 设置倒计时
let iv = setInterval(() => {
let suffix;
switch (this.seconds % 3) {
case 2:
suffix = "...";
break;
case 1:
suffix = "..";
break;
default:
suffix = ".";
break;
}
this.loading = "数据加载中" + suffix;
this.seconds--;
if (this.seconds == 0) {
clearInterval(iv);
}
}, 1000);
}
页面会在动画播放完成后跳转到商城首页,使用setTimeout()设置定时跳转即可。这里在播放动画时预加载了首页需要的数据,作为页面参数跳转,可以加快商城页的展示速度,提升用户体验。
文章后续内容和相关附件可以点击下面的原文链接前往学习
原文链接: https://harmonyos.51cto.com/posts/3160#bkwz
https://harmonyos.51cto.com/#bkwz

















