HTML5实现像素化推荐缩放法:先将原图绘制到小尺寸canvas并关闭imageSmoothingEnabled,再拉伸显示;需整数倍缩放以保证像素对齐;手动操作getImageData适用于精确控制像素块颜色,但要注意跨域和性能问题。

HTML5 本身没有直接的“像素化”滤镜 API,但用 Canvas + getImageData + putImageData 可以手动实现——关键不在“加滤镜”,而在“降采样再上采样”。
用 canvas 缩放再拉伸实现快速像素化
这是最轻量、兼容性最好、也最常用的方法:先将原图绘制到小尺寸 canvas,再用大尺寸 canvas 拉伸显示。浏览器默认使用双线性插值,所以要关掉它才能得到硬边像素块。
实操要点:
- 设置目标 canvas 的
ctx.imageSmoothingEnabled = false(Chrome/Firefox/Edge 均支持) - 先用
drawImage把原图缩放到小尺寸(如 32×32),再 draw 到大 canvas 上 - 像素块大小 = 原图宽高 ÷ 缩放后宽高,比如原图 640×480 → 缩到 64×48,则每块像素是 10×10
- 注意:缩放比例必须是整数倍才保证像素对齐;非整数倍时边缘可能模糊或错位
const canvas = document.getElementById('pixelCanvas');
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
// 假设 img 已加载完成
const pixelSize = 16;
const smallWidth = Math.floor(img.width / pixelSize);
const smallHeight = Math.floor(img.height / pixelSize);
// 绘制到小画布(内存中)
const tempCanvas = document.createElement('canvas');
tempCanvas.width = smallWidth;
tempCanvas.height = smallHeight;
const tempCtx = tempCanvas.getContext('2d');
tempCtx.drawImage(img, 0, 0, smallWidth, smallHeight);
// 拉伸回原尺寸(开启像素化)
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(tempCanvas, 0, 0, smallWidth, smallHeight, 0, 0, img.width, img.height);
用 getImageData 手动取样做精确像素化
当需要控制每个像素块的颜色来源(比如取平均值、中位数、左上角值),或想做动态像素粒度调节时,就得操作像素数据。性能比缩放法低,但更可控。
立即学习“前端免费学习笔记(深入)”;
常见错误现象:SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D' —— 图片跨域未处理,务必在 img 上加 crossOrigin="anonymous" 属性。
实操要点:
- 先用
drawImage把图片画到 canvas(同域或已配 CORS) - 调用
ctx.getImageData(0, 0, w, h)获取Uint8ClampedArray - 遍历像素,按
pixelSize步长取样,把每个块的左上角颜色(或计算出的颜色)填满整个块 - 注意:RGBA 数据是每 4 个字节一组(R,G,B,A),索引为
(y * width + x) * 4
function pixelize(ctx, imageData, pixelSize) {
const { width, height, data } = imageData;
const newData = new Uint8ClampedArray(data.length);
for (let y = 0; y < height; y += pixelSize) {
for (let x = 0; x < width; x += pixelSize) {
const srcIdx = (y width + x) 4;
const r = data[srcIdx], g = data[srcIdx+1], b = data[srcIdx+2], a = data[srcIdx+3];
// 填充整个像素块
for (let dy = 0; dy < pixelSize && y+dy < height; dy++) {
for (let dx = 0; dx < pixelSize && x+dx < width; dx++) {
const dstIdx = ((y+dy) * width + (x+dx)) * 4;
newData[dstIdx] = r;
newData[dstIdx+1] = g;
newData[dstIdx+2] = b;
newData[dstIdx+3] = a;
}
}
}}
const newImageData = new ImageData(newData, width, height);
ctx.putImageData(newImageData, 0, 0);
}
CSS filter: url(#pixel) 不实用,别走这条路
虽然 SVG 滤镜能写 + 模拟像素化,但实际中:filter: url(#pixel) 在多数浏览器里不支持动态参数,无法响应式调整像素大小;且性能差、渲染延迟明显;移动端基本不可用。
结论很直接:不用 SVG 滤镜做像素化。不是不能写,而是写了也难维护、难调试、难适配。
真正要注意的复杂点,其实是图像加载时机和跨域策略——img.onload 必须等资源就绪再绘图,而 CORS 错误不会报红,只会静默失败导致 getImageData 报 SecurityError。这两个地方卡住的人,远多于算法本身。










