canvas 马赛克效果

603 阅读1分钟

课件地址

github.com/buglas/canv…

我们可以逐行列遍历ImageData 对象里的像素,将特定区域的颜色变成色块,从而变成马赛克效果。

image-20220511220237153

整体代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>马赛克效果</title>
    <style>
        body{margin: 0;overflow: hidden}
        #canvas{background: antiquewhite;}
    </style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
    const canvas=document.getElementById('canvas');
    //canvas充满窗口
    canvas.width=window.innerWidth;
    canvas.height=window.innerHeight;
    const ctx=canvas.getContext('2d');

    //图像源
    const img=new Image();
    img.src='./images/wns.jpg';
    img.onload=render;

    //色块尺寸
    let size=15;

    function render() {
        //图像尺寸
        const {width,height}=img;

        /*1.在canvas 中绘制图像*/
        ctx.drawImage(img,0,0);

        /*2.从canvas 中获取图像的ImageData*/
        const imgDt=ctx.getImageData(0,0,width,height);
        const data=imgDt.data;

        ctx.fillRect(0,0,width,height)
        /*行列遍历*/
        for(let y=0;y<height;y+=size){
            for(let x=0;x<width;x+=size){
                const i=(y*width+x)*4
                const [r,g,b]=[
                    data[i],
                    data[i+1],
                    data[i+2],
                ]
                ctx.fillStyle=`rgb(${r},${g},${b})`
                // ctx.fillRect(x,y,size,size)
                ctx.beginPath()
                ctx.arc(x,y,size/2,0,Math.PI*2)
                ctx.fill()
            }
        }

    }
</script>
</body>
</html>

总结

我们可以通过不同的算法,对ImageData 中的像素进行不同的处理。比如调整图片的色调,检测图像边缘,实现艺术效果……

image-20220427212822777