CSS/SCSS 做一个心跳的动画 keyframe

CSS/SCSS 做一个心跳的动画

一、心电图数据化

做动画,需要动画曲线,心跳的曲线自然是心电图,网上随便找一个差不多的,选取完整的一部分

1. 横向10等分

找到基线,横向10等分。
整个图是一个心跳周期,10等分一会好算时间,对应 keyframe 中的 10% 20% 30% ...
CSS/SCSS 做一个心跳的动画 keyframe_第1张图片

2. 纵向10等分

以基线为基准,找到上半部分最高的位置作为最高处,从基线到最高处10等分。
再复制一份上面的坐标到下面。
CSS/SCSS 做一个心跳的动画 keyframe_第2张图片

3. 找到曲线中的关键点

找到曲线的关键点,这些就是我们要在动画中记录的变化位置
CSS/SCSS 做一个心跳的动画 keyframe_第3张图片

二、写动画 css

拿到图形数据之后,我们就需要对它进行代码化了。
其实就是把上面每个关键点都写到动画 css 的关键帧中。

这里我们用 SCSS 写,因为它可以使用算式。

SCSS 的使用教程移步这里: SCSS 日常基础用法

原理

CSS/SCSS 做一个心跳的动画 keyframe_第4张图片
动画时间轴
图中横向的 1-10 对应 keyframe 中的 from,10%,20%,30%...to

css 缩放实现
css 中使用 transform: scale() 实现对图形的放大缩小动画

css 动画缩放的比例如何算
图形的原始大小是 scale(1)
我们先设置一个缩放的最大值,比如 scale(1 + 0.2),那么变化的增幅就是 0.2,这个 0.2 就代表图中 从基线位置到最高点的距离 ,这样就可以计算出每个关键点的增幅。
比如:第二个关键点的位置差不多是 (横向 12%,纵向 10%),那么css关键帧中就是

开写 SCSS 动画

// 定义一个变量:增幅
$max-amplitude: 0.2;
// 第一帧的增幅就是:$max-amplitude * 0.1
@keyframes heart-bounce {
  from {transform: scale(1);}
  12% {transform: scale(1 + $max-amplitude * 0.1);}
  to {transform: scale(1);}
}

按照图中位置补齐所有关键点就是

@keyframes heart-bounce {
  from {transform: scale(1);}
  12% {transform: scale(1 + $max-amplitude * 0.1);}
  20% {transform: scale(1 - $max-amplitude * 0.05);}
  28% {transform: scale(1 - $max-amplitude * 0.1);}
  32% {transform: scale(1 + $max-amplitude * 1);}
  38% {transform: scale(1 - $max-amplitude * 0.2);}
  50% {transform: scale(1 - $max-amplitude * 0);}
  58% {transform: scale(1 - $max-amplitude * 0.1);}
  70% {transform: scale(1 - $max-amplitude * 0.5);}
  80% {transform: scale(1 - $max-amplitude * 0.1);}
  to {transform: scale(1);}
}

这样生成的 css 是这样的

@keyframes heart-bounce {
  from {transform: scale(1); }
  12% {transform: scale(1.02); }
  20% {transform: scale(0.99); }
  28% {transform: scale(0.98); }
  32% {transform: scale(1.2); }
  38% {transform: scale(0.96); }
  50% {transform: scale(1); }
  58% {transform: scale(0.98); }
  70% {transform: scale(0.9); }
  80% {transform: scale(0.98); }
  to {transform: scale(1); } }
/*# sourceMappingURL=heartbeat.css.map */

这样动画代码出来了,再定义一个类名 .heart-beat 来调用这个动画

.heart-beat{
    animation-duration: 1s; // 一个完整动画的持续时间
    animation-iteration-count: infinite; // 动画循环次数:无限循环
    animation-name: heart-bounce; // 调用的动画名,对应上面的 .heart-bounce
}

这样,在你需要跳动的图片或文字上使用该 class 即可

效果如图:

你可能感兴趣的:(前端,css,css3,sass,scss)