前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >CSS3: animate 帧动画和雪碧图-完成一个盒子打开动画

CSS3: animate 帧动画和雪碧图-完成一个盒子打开动画

作者头像
西南_张家辉
发布2021-02-02 10:17:38
1.3K0
发布2021-02-02 10:17:38
举报

写在最前面

  • 最近做一个关于抽奖活动的项目,会涉及到很多动画,这里来探讨一下 scss 函数和 css 动画的制作

需求:如图

  • 一个打开的盒子,其中有许多不规则的星星✨不规则的运动动,看着这个复杂的动画,我不禁周冬雨附身--小黄鸭眉头一皱.gif。
  • 已经好久没写动画的我该如何入手,在仅限的 css 知识中知道 animate 动画。
image
image

思考

  • 1、盒子弹跳动画
  • 2、光幕出现,阴影的出现动画
  • 3、盖子不规则飞行
  • 4、星星不规则飞行

实现

  • 1、transform: scaleY() translate() 实现盒子弹跳
  • 2、opacity 实现光幕和阴影
  • 3、transform: rotateZ() 盖子飞行,翻转
  • 4、top left transform: translate() 星星运动

大概的思路都有了开始动手,写一个盖子飞行的动画

// 盒子居中布局
.stars{
    opacity: 0;
}

.box{
    top:50%;
    left:50%;
    position:absolute;
    transform: translate(-50%,-50%);
}

// 基础 keyframes  函数
@mixin keyframes($animationName) {
  @keyframes #{$animationName} {
      @content;
  }
}

// 由于是 translate 布局,这里改变定位使用 translate
@mixin animate-bounce($name:'bounce', $time: 1.5s, $animateFunc: linear) {
  animation: $name $time ?animateFunc;
  @include keyframes($name) {
        0% {
            transform: scaleY(1) translate(-50%, -50%);
        }
        8% {
            transform: scaleY(0.98) translate(-50%, -48%);
        }
        50% {
            transform: scaleY(1) translate(-50%, -70%);
        }
        100% {
            transform: scaleY(1) translate(-50%, -50%);
        }
    }
  }
}

@mixin animate-box-cover-fly($name:'box-cover-fly', $time: 1.5s, $animateFunc: linear){
    animation: $name $time ?animateFunc;
  @include keyframes($name) {
        0% {
            top: 23%;
            left: 50%;
        }
        100% {
            top: 5%;
            left: 62%;
            transform: translate(-20%, -50%) rotateZ(26deg);
        }
    }
  }
}

// 盒子弹跳
.box-bounce{
    @include animate-bounce('bounce');
}

.box-cover-fly{
    @include animate-box-cover-fly('box-cover-fly');
}

思考

  • 写到这里时候发现代码量会很多,即使用函数的形式,复写动画路径,具体实现中,发现效果并不好也不能完全复刻设计给的动画。
  • 然后 google 了一下动画的实现方法,发现了帧动画,和雪碧图。虽然这两个知识点早就听说过,但是使用的时候都是分开使用的。结合起来的时候也能做动画效果,说做就做,先写一个 demo
  • html
 <div className="step-box" />
复制代码
@mixin animate-spite-box($width: 134px) {
  background: url('https://uploads.codesandbox.io/uploads/user/abc364e4-ea65-4398-a1dc-df2645675b64/U59a-lightbulb.png') 0 0 no-repeat;
  background-size: cover;
  animation: spite-box 1s steps(4) infinite;
  @include keyframes(spite-box) {
    from {
      background-position: -8*$width;
     }
     to {
      background-position: -12*$width;
     }
  }
}

$box-width: 134px
$box-height: 113px;
.step-box{
    width: $box-width;
    height: $box-height;
    @include animate-spite-box($box-width);
}

先来看一个栗子

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 需求:如图
  • 思考
  • 实现
  • 思考
  • 先来看一个栗子
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档