js实现图片抖动效果
实现图片抖动效果的几种方法
使用CSS动画和JavaScript触发
CSS中定义关键帧动画实现抖动效果,通过JavaScript动态添加或移除类名控制动画播放。
@keyframes shake {
0%, 100% { transform: translateX(0); }
10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
20%, 40%, 60%, 80% { transform: translateX(5px); }
}
.shake-effect {
animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
}
const img = document.querySelector('img');
img.addEventListener('click', () => {
img.classList.add('shake-effect');
setTimeout(() => img.classList.remove('shake-effect'), 500);
});
纯JavaScript实现随机位移
通过定时器快速修改图片位置实现抖动,适合需要精细控制抖动的场景。
function shakeImage(element, duration = 500, intensity = 5) {
let startTime = null;
const originalPosition = element.getBoundingClientRect();
function animate(timestamp) {
if (!startTime) startTime = timestamp;
const progress = timestamp - startTime;
const percent = Math.min(progress / duration, 1);
const x = (Math.random() * 2 - 1) * intensity * (1 - percent);
const y = (Math.random() * 2 - 1) * intensity * (1 - percent);
element.style.transform = `translate(${x}px, ${y}px)`;
if (progress < duration) {
requestAnimationFrame(animate);
} else {
element.style.transform = '';
}
}
requestAnimationFrame(animate);
}
// 使用示例
const img = document.getElementById('target-image');
img.addEventListener('mouseover', () => shakeImage(img));
使用GSAP动画库
GSAP提供更强大的动画控制能力,适合复杂抖动效果。
import { gsap } from "gsap";
function shakeWithGSAP(element) {
gsap.to(element, {
x: () => Math.random() * 10 - 5,
y: () => Math.random() * 10 - 5,
duration: 0.1,
repeat: 5,
onComplete: () => gsap.set(element, { x: 0, y: 0 })
});
}
物理模拟抖动效果
模拟弹簧物理效果实现更自然的抖动,需要引入简单物理计算。
function physicsShake(element, power = 10) {
let velocity = { x: power, y: -power };
const damping = 0.8;
const position = { x: 0, y: 0 };
function update() {
velocity.x *= damping;
velocity.y *= damping;
position.x += velocity.x;
position.y += velocity.y;
element.style.transform = `translate(${position.x}px, ${position.y}px)`;
if (Math.abs(velocity.x) > 0.1 || Math.abs(velocity.y) > 0.1) {
requestAnimationFrame(update);
} else {
element.style.transform = '';
}
}
update();
}
注意事项
- 性能优化:对于频繁触发的抖动效果,建议使用CSS动画或硬件加速属性如
transform - 可访问性:避免对光敏感用户造成不适,可提供关闭选项
- 移动端适配:可能需要调整抖动幅度以适应不同屏幕尺寸
- 动画中止:实现清除抖动状态的方法,防止动画累积
以上方法可根据具体需求选择,CSS方案适合简单场景,JavaScript方案提供更多控制,GSAP适合复杂动画需求。







