css制作心跳效果

使用CSS动画制作心跳效果
通过CSS的@keyframes和transform属性可以创建简单的心跳动画效果。以下是实现方法:

基础心跳动画
.heartbeat {
animation: heartbeat 1.5s ease-in-out infinite both;
}
@keyframes heartbeat {
0% {
transform: scale(1);
}
14% {
transform: scale(1.3);
}
28% {
transform: scale(1);
}
42% {
transform: scale(1.3);
}
70% {
transform: scale(1);
}
}
带阴影增强的版本
.pulse {
animation: pulse 2s infinite;
}
@keyframes pulse {
0% {
transform: scale(0.95);
box-shadow: 0 0 0 0 rgba(255, 0, 0, 0.7);
}
70% {
transform: scale(1.1);
box-shadow: 0 0 0 10px rgba(255, 0, 0, 0);
}
100% {
transform: scale(0.95);
box-shadow: 0 0 0 0 rgba(255, 0, 0, 0);
}
}
使用CSS变量控制参数
:root {
--heartbeat-scale: 1.2;
--heartbeat-duration: 1s;
}
.custom-heartbeat {
animation: custom-heartbeat var(--heartbeat-duration) ease-in-out infinite;
}
@keyframes custom-heartbeat {
0%, 100% {
transform: scale(1);
}
50% {
transform: scale(var(--heartbeat-scale));
}
}
应用于SVG心形图标
<svg class="heart" viewBox="0 0 32 32">
<path d="M23.6 2c-3.4 0-6.3 2.7-7.6 5.6-1.3-2.9-4.2-5.6-7.6-5.6C4.2 2 0 6.2 0 11c0 11 12 19 16 19 4 0 16-8 16-19 0-4.8-4.2-9-8.4-9z"/>
</svg>
<style>
.heart {
width: 100px;
fill: red;
animation: heartbeat 1s infinite alternate;
}
</style>
性能优化建议
- 使用
will-change: transform提升动画性能 - 避免同时激活过多心跳元素
- 考虑使用
requestAnimationFrame替代CSS动画处理复杂场景
这些方法可以单独使用也可以组合使用,根据实际需求调整动画持续时间、缩放比例和缓动函数。






