js实现图片变换
使用JavaScript实现图片变换
方法一:通过修改src属性切换图片
const image = document.getElementById('myImage');
const imageSources = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
let currentIndex = 0;
function changeImage() {
currentIndex = (currentIndex + 1) % imageSources.length;
image.src = imageSources[currentIndex];
}
// 定时切换
setInterval(changeImage, 2000);
方法二:使用CSS类切换实现淡入淡出效果

const image = document.getElementById('myImage');
const imageSources = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
let currentIndex = 0;
function fadeImage() {
image.classList.add('fade-out');
setTimeout(() => {
currentIndex = (currentIndex + 1) % imageSources.length;
image.src = imageSources[currentIndex];
image.classList.remove('fade-out');
}, 500);
}
// 添加CSS样式
const style = document.createElement('style');
style.textContent = `
.fade-out {
opacity: 0;
transition: opacity 0.5s ease;
}
`;
document.head.appendChild(style);
setInterval(fadeImage, 3000);
方法三:使用Canvas实现高级图像变换

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const images = [
new Image(), new Image(), new Image()
];
images.forEach((img, i) => img.src = `image${i+1}.jpg`);
let currentImg = 0;
let alpha = 0;
function draw() {
ctx.globalAlpha = 1;
ctx.drawImage(images[currentImg], 0, 0, canvas.width, canvas.height);
if(alpha < 1) {
ctx.globalAlpha = alpha;
ctx.drawImage(images[(currentImg + 1) % images.length], 0, 0, canvas.width, canvas.height);
alpha += 0.01;
} else {
alpha = 0;
currentImg = (currentImg + 1) % images.length;
}
requestAnimationFrame(draw);
}
images[0].onload = function() {
canvas.width = images[0].width;
canvas.height = images[0].height;
draw();
};
方法四:使用WebGL实现3D图片变换
const canvas = document.getElementById('glCanvas');
const gl = canvas.getContext('webgl');
// 初始化WebGL程序、着色器等
// 加载纹理
const textures = [];
const imageUrls = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
imageUrls.forEach((url, i) => {
textures[i] = gl.createTexture();
const image = new Image();
image.onload = function() {
gl.bindTexture(gl.TEXTURE_2D, textures[i]);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
};
image.src = url;
});
let currentTexture = 0;
let mixFactor = 0;
function render() {
// 设置混合因子uniform
// 绑定两个纹理
// 绘制场景
mixFactor += 0.01;
if(mixFactor >= 1) {
mixFactor = 0;
currentTexture = (currentTexture + 1) % textures.length;
}
requestAnimationFrame(render);
}
render();
注意事项
- 确保图片已完全加载后再进行变换操作
- 对于响应式设计,需要考虑图片尺寸适应问题
- 大量图片变换时注意内存管理
- 移动端需考虑性能优化
以上方法可根据项目需求选择适合的实现方式,从简单的图片切换到复杂的3D变换都能满足不同场景需求。






