How to pixelate an image with canvas and javascript

后端 未结 2 559
傲寒
傲寒 2020-12-01 06:42

I\'ve been experimenting a bit with the canvas element and was curious how to pull off an effect.

I\'ve somewhat got what I\'m looking for from a collection of tutor

相关标签:
2条回答
  • 2020-12-01 07:06

    Just keep in mind, there is a few javascript libraries doing same effect, for example pixelate or close-pixelate.

    0 讨论(0)
  • 2020-12-01 07:24

    You don't need to iterate pixel buffer to create a pixelating effect.

    Simply turn off image smoothing and enlarge a small version of the image to the canvas. This will also mean you can use any image as source (CORS-wise).

    Example:

    Fiddle demo

    // get a block size (see demo for this approach)
    var size = blocks.value / 100,
        w = canvas.width * size,
        h = canvas.height * size;
    
    // draw the original image at a fraction of the final size
    ctx.drawImage(img, 0, 0, w, h);
    
    // turn off image aliasing
    ctx.msImageSmoothingEnabled = false;
    ctx.mozImageSmoothingEnabled = false;
    ctx.webkitImageSmoothingEnabled = false;
    ctx.imageSmoothingEnabled = false;
    
    // enlarge the minimized image to full size    
    ctx.drawImage(canvas, 0, 0, w, h, 0, 0, canvas.width, canvas.height);
    

    In the demo you can animate this effect to see that the performance is very good compared to an pixel iterating method as the browser takes care of the "pixelation" internally in compiled code.

    0 讨论(0)
提交回复
热议问题