css制作心跳效果
使用CSS动画制作心跳效果
通过CSS的@keyframes和transform属性可以创建简单的心跳动画效果。核心原理是周期性缩放元素大小,模拟心跳的膨胀收缩。
基础实现代码:
.heartbeat {
animation: heartbeat 1.5s ease-in-out infinite;
}
@keyframes heartbeat {
0% {
transform: scale(1);
}
14% {
transform: scale(1.3);
}
28% {
transform: scale(1);
}
42% {
transform: scale(1.3);
}
70% {
transform: scale(1);
}
}
增强视觉效果
添加颜色变化和阴影效果使心跳更逼真:
.heartbeat {
width: 100px;
height: 100px;
background-color: #ff0000;
box-shadow: 0 0 40px #ff0000;
animation: heartbeat 1.5s ease-in-out infinite;
}
@keyframes heartbeat {
0% {
transform: scale(1);
box-shadow: 0 0 10px #ff0000;
}
50% {
transform: scale(1.1);
background-color: #ff3333;
box-shadow: 0 0 30px #ff0000;
}
100% {
transform: scale(1);
box-shadow: 0 0 10px #ff0000;
}
}
SVG实现心跳效果
使用SVG路径动画可创建更精确的心脏图形动画:
<svg width="100" height="100" viewBox="0 0 24 24">
<path
d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"
fill="red"
class="heartbeat"
/>
</svg>
.heartbeat {
animation: heartbeat 1s infinite;
transform-origin: center;
}
@keyframes heartbeat {
0% { transform: scale(1); }
25% { transform: scale(1.1); }
50% { transform: scale(1); }
75% { transform: scale(1.1); }
100% { transform: scale(1); }
}
性能优化建议
使用will-change属性提升动画性能:
.heartbeat {
will-change: transform;
/* 其他动画属性 */
}
考虑使用requestAnimationFrame实现更流畅的动画,但这需要JavaScript配合。纯CSS方案在大多数现代浏览器中已能提供良好的性能表现。







