js实现图片渐变效果
使用CSS和JavaScript实现图片渐变效果
在网页中实现图片渐变效果可以通过CSS的opacity属性和JavaScript的定时器或动画API来完成。以下是几种常见方法:
CSS transition实现淡入淡出
通过修改CSS的opacity属性并添加过渡效果:
.fade-image {
opacity: 0;
transition: opacity 2s ease-in-out;
}
const img = document.querySelector('.fade-image');
img.style.opacity = 1; // 触发渐变显示
requestAnimationFrame实现平滑动画
使用JavaScript的动画API实现更精细的控制:
function fadeIn(element, duration) {
let start = null;
const step = timestamp => {
if (!start) start = timestamp;
const progress = timestamp - start;
const opacity = Math.min(progress / duration, 1);
element.style.opacity = opacity;
if (progress < duration) {
requestAnimationFrame(step);
}
};
requestAnimationFrame(step);
}
Canvas实现高级渐变效果
对于更复杂的渐变效果,可以使用Canvas:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = function() {
let alpha = 0;
const fadeIn = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.globalAlpha = alpha;
ctx.drawImage(img, 0, 0);
alpha += 0.01;
if (alpha < 1) requestAnimationFrame(fadeIn);
};
fadeIn();
};
img.src = 'image.jpg';
使用Web Animations API
现代浏览器支持的Web Animations API:
const img = document.querySelector('img');
img.animate([
{ opacity: 0 },
{ opacity: 1 }
], {
duration: 1000,
fill: 'forwards'
});
交叉观察器实现滚动渐变
结合Intersection Observer实现滚动时渐变:
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.style.opacity = 1;
}
});
}, { threshold: 0.1 });
document.querySelectorAll('.fade-image').forEach(img => {
observer.observe(img);
});
每种方法适用于不同场景,CSS transition最简单,requestAnimationFrame提供更精细控制,Canvas适合复杂效果,Web Animations API是现代标准方案。







