js实现扫描图片效果
实现图片扫描效果的JavaScript方法
方法一:使用Canvas逐行绘制
通过Canvas逐行绘制图片模拟扫描效果。
const img = new Image();
img.src = 'image.jpg';
img.onload = function() {
const canvas = document.getElementById('scanCanvas');
const ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
let currentLine = 0;
const scanInterval = setInterval(() => {
ctx.drawImage(img, 0, currentLine, img.width, 1, 0, currentLine, img.width, 1);
currentLine++;
if (currentLine >= img.height) clearInterval(scanInterval);
}, 10);
};
方法二:CSS遮罩动画
结合CSS动画实现扫描线效果。
const imgElement = document.getElementById('scanImage');
imgElement.style.position = 'relative';
imgElement.style.overflow = 'hidden';
const scanLine = document.createElement('div');
scanLine.style.position = 'absolute';
scanLine.style.width = '100%';
scanLine.style.height = '2px';
scanLine.style.backgroundColor = 'rgba(0,255,0,0.5)';
scanLine.style.animation = 'scan 3s linear infinite';
imgElement.appendChild(scanLine);
// 添加CSS样式
const style = document.createElement('style');
style.textContent = `
@keyframes scan {
0% { top: 0; }
100% { top: 100%; }
}
`;
document.head.appendChild(style);
方法三:WebGL着色器
使用WebGL实现高级扫描效果。
const vertexShaderSource = `
attribute vec2 a_position;
void main() {
gl_Position = vec4(a_position, 0, 1);
}
`;
const fragmentShaderSource = `
precision mediump float;
uniform sampler2D u_texture;
uniform float u_scanPosition;
void main() {
vec2 uv = gl_FragCoord.xy / resolution.xy;
vec4 color = texture2D(u_texture, uv);
float scanLine = step(uv.y, u_scanPosition);
gl_FragColor = color * scanLine;
}
`;
// 初始化WebGL并设置动画循环
方法四:SVG滤镜效果
通过SVG滤镜创建扫描线纹理。

const svgFilter = `
<svg width="0" height="0">
<filter id="scanlines">
<feTurbulence type="fractalNoise" baseFrequency="0.5" numOctaves="1" stitchTiles="stitch"/>
<feColorMatrix type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 5 -2"/>
</filter>
</svg>
`;
document.body.insertAdjacentHTML('afterbegin', svgFilter);
document.getElementById('scanImage').style.filter = 'url(#scanlines)';
注意事项
- 性能优化:对于大图片建议使用方法三WebGL方案
- 移动端适配:CSS方案在移动设备上可能有更好的性能表现
- 效果增强:可以添加发光效果增强扫描线的视觉冲击力
每种方法都可以通过调整参数获得不同的扫描效果,根据具体需求选择最适合的实现方式。






