在小程序中用一张 PNG 实现两个动效

栏目: Html · 发布时间: 6年前

内容简介:无法控制 gif 图的执行过程,需要通过切换图片源来实现两个动效的切换。图片放在代码包中:动效的 gif 图尺寸一般比较大,放在代码包中会超出代码包 2M 大小的限制。使用网络图片:切换的时候需要加载图片,会出现动效不连贯的问题

无法控制 gif 图的执行过程,需要通过切换图片源来实现两个动效的切换。

图片放在代码包中:动效的 gif 图尺寸一般比较大,放在代码包中会超出代码包 2M 大小的限制。

使用网络图片:切换的时候需要加载图片,会出现动效不连贯的问题

缓存在本地:使用 wx.downloadFile 缓存在本地,但本地缓存有 10M 的限制,一不小心也会超哦~

2. 使用 APNG

问题同 gif,兼容性也有一定的问题。

3. 使用 PNG 序列(雪碧图)

单个动效的实现方案可以参考 张鑫旭大佬的文章: 小tips: CSS或JS实现gif动态图片的停止与播放

为了避免切换动效时出现短暂的空白的状态,可使用 PNG 序列的方式实现:将两个动效的序列图连接在一起。

那用一张 PNG 来做两个动效怎么实现呢?以一张 80 帧的 PNG 序列为例,前 40 帧为第一个动效,后 40 帧为第二个动效。执行时间均为2s。

@keyframes animate-default {
  0% {
    background-position: 0;
  }

  100% {
    background-position: 50%;
  }
}

.animate-default {
    animation: animate-default steps(39) 2s infinite forwards;
}

@keyframes animate-click {
  0% {
    background-position: 50%;
  }

  100% {
    background-position: 100%;
  }
}

.animate-click {
    animation: animate-click steps(39) 2s 1 forwards;
}
复制代码

but,现实总是很残酷,并不是我们想要的效果。

在小程序中用一张 PNG 实现两个动效

那问题出在哪里呢?

单帧图片的宽度为 384px,图片执行到第 40 张的时候其实位置为 384 * 39 = 14976,我们将 animate-default 动效的 100% 位置改为 -14976px,同理将 animate-click 动效的 0% 位置改为 384 * 40 即 -15360px 即可。

但为了更好的适配不同的设备,我们选用了 rpx 为单位,虽然在 750 设备上动画正常,但切换设备,动画又坏掉了...摩擦,摩擦,在光滑的地板上...

请忽略后面的背景~

在小程序中用一张 PNG 实现两个动效

不能用 px 为单位,不能用 rpx 为单位,那以百分比的形式设置 background-position,我们该如何实现呢?

敲黑板,重点来了!!

敲黑板,重点来了!!

敲黑板,重点来了!!

background-position 的计算公式(from《CSS 世界》)是:

percentX = positionX /(容器宽度 - 图片宽度);

percentY = positionY /(容器宽度 - 图片宽度);

所以本例中,

-14976 / (384 - 384 * 80 ),约 0.49367089;

-15360 / (384 - 384 * 80),约 0.50632911。

@keyframes animate-default {
  0% {
    background-position: 0;
  }

  100% {
    background-position: 49.367%;
  }
}

.animate-default {
    animation: animate-default steps(39) 2s infinite forwards;
}

@keyframes animate-click {
  0% {
    background-position: 50.633%;
  }

  100% {
    background-position: 100%;
  }
}

.animate-click {
    animation: animate-click steps(39) 2s infinite forwards;
}
复制代码
在小程序中用一张 PNG 实现两个动效

在点击后切换 class,再切换回来~OK啦,完美!


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Concepts, Techniques, and Models of Computer Programming

Concepts, Techniques, and Models of Computer Programming

Peter Van Roy、Seif Haridi / The MIT Press / 2004-2-20 / USD 78.00

This innovative text presents computer programming as a unified discipline in a way that is both practical and scientifically sound. The book focuses on techniques of lasting value and explains them p......一起来看看 《Concepts, Techniques, and Models of Computer Programming》 这本书的介绍吧!

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具