js实现图片特效
图片滤镜效果
使用Canvas的getImageData和putImageDataAPI修改像素值实现基础滤镜:
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.drawImage(imgElement, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
// 灰度效果
for (let i = 0; i < data.length; i += 4) {
const avg = (data[i] + data[i+1] + data[i+2]) / 3;
data[i] = data[i+1] = data[i+2] = avg;
}
ctx.putImageData(imageData, 0, 0);
动态粒子化效果
通过将图片分解为随机运动的粒子:

class Particle {
constructor(x, y, color) {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.targetX = x;
this.targetY = y;
this.color = color;
}
update() {
this.x += (this.targetX - this.x) * 0.1;
this.y += (this.targetY - this.y) * 0.1;
}
}
// 从图片数据创建粒子阵列
const particles = [];
for (let y = 0; y < imageData.height; y += 5) {
for (let x = 0; x < imageData.width; x += 5) {
const index = (y * imageData.width + x) * 4;
particles.push(new Particle(
x, y,
`rgba(${data[index]}, ${data[index+1]}, ${data[index+2]}, ${data[index+3]})`
));
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(p => {
p.update();
ctx.fillStyle = p.color;
ctx.fillRect(p.x, p.y, 3, 3);
});
requestAnimationFrame(animate);
}
3D翻转过渡
使用CSS 3D变换实现立体翻转效果:

.flip-container {
perspective: 1000px;
}
.flipper {
transition: transform 0.8s;
transform-style: preserve-3d;
}
.flipper.flipped {
transform: rotateY(180deg);
}
.front, .back {
backface-visibility: hidden;
position: absolute;
}
.back {
transform: rotateY(180deg);
}
图片拖拽变形
通过监听鼠标事件实现橡皮筋拉伸效果:
let isDragging = false;
let startX, startY;
canvas.addEventListener('mousedown', (e) => {
isDragging = true;
[startX, startY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mousemove', (e) => {
if (!isDragging) return;
ctx.globalCompositeOperation = 'source-over';
ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
[startX, startY] = [e.offsetX, e.offsetY];
});
WebGL高级特效
使用GLSL着色器实现波浪扭曲:
const shaderScript = `
precision mediump float;
uniform sampler2D texture;
uniform float time;
varying vec2 vUV;
void main() {
vec2 uv = vUV;
uv.x += sin(uv.y * 10.0 + time) * 0.05;
gl_FragColor = texture2D(texture, uv);
}
`;
// 初始化WebGL程序后传递时间变量
function render() {
gl.uniform1f(timeUniform, performance.now() / 1000);
gl.drawArrays(gl.TRIANGLES, 0, 6);
requestAnimationFrame(render);
}






