js实现图片动画
使用 JavaScript 实现图片动画
方法 1:使用 CSS 动画和 JavaScript 控制
通过 JavaScript 动态添加或移除 CSS 类来控制动画。
// HTML 结构
<img id="animated-image" src="image.jpg" class="static">
// CSS 定义
.static {
transition: transform 0.5s ease;
}
.animated {
transform: rotate(360deg) scale(1.2);
}
// JavaScript 控制
const image = document.getElementById('animated-image');
image.addEventListener('click', () => {
image.classList.toggle('animated');
});
方法 2:使用 requestAnimationFrame 实现自定义动画
适用于需要精细控制动画每一帧的情况。

const image = document.getElementById('animated-image');
let position = 0;
let direction = 1;
function animate() {
position += direction * 2;
if (position > 100 || position < 0) {
direction *= -1;
}
image.style.transform = `translateX(${position}px)`;
requestAnimationFrame(animate);
}
animate();
方法 3:使用 GSAP 动画库
GSAP 是一个强大的动画库,适合复杂动画场景。

// 引入 GSAP 库后
gsap.to("#animated-image", {
duration: 2,
x: 100,
y: 50,
rotation: 180,
ease: "bounce.out",
repeat: -1,
yoyo: true
});
方法 4:Canvas 动画
适用于需要在画布上实现复杂动画的情况。
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.src = 'image.jpg';
let x = 0;
img.onload = function() {
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, x, 50, 100, 100);
x = (x + 2) % canvas.width;
requestAnimationFrame(draw);
}
draw();
};
方法 5:SVG 图片动画
适用于矢量图形的动画效果。
// HTML 中的 SVG
<svg id="svg-container" width="500" height="500">
<image id="svg-image" href="image.jpg" x="0" y="0" width="100" height="100"/>
</svg>
// JavaScript 动画
const svgImage = document.getElementById('svg-image');
let angle = 0;
function updateSvgAnimation() {
angle = (angle + 1) % 360;
svgImage.setAttribute('transform', `rotate(${angle} 50 50)`);
requestAnimationFrame(updateSvgAnimation);
}
updateSvgAnimation();
动画性能优化建议
- 使用
transform和opacity属性进行动画,这些属性不会触发重排 - 避免在动画期间修改
width、height、top、left等布局属性 - 对于复杂动画,考虑使用
will-changeCSS 属性提前告知浏览器 - 适当使用
requestAnimationFrame而不是setTimeout或setInterval
浏览器兼容性考虑
- 现代浏览器都支持 CSS 动画和
requestAnimationFrame - 对于旧版浏览器,可能需要添加前缀或使用 polyfill
- GSAP 等库已经处理了大部分兼容性问题






