hello and welcome to red stapler channel in this tutorial we will show you how to
create pixelated image with JavaScript and canvas in just a few minutes let's
check it out
so here's the example page there is only one image on it and nothing else except
few CSS rules for center alignment first we will start with loading image to
canvas so let's create a canvas element
then create a new image object we'll use this to load the image on this page
before we put it into canvas to start loading the image we just need to set
the image source now loading the image takes some times to finish so we can't
continue the processing right away we will need to create event listener to
trigger when the loading is finished so let's bind onload event listener to
the image object then inside will print the console to see if it works okay now
we will continue the image processing first we will remove the old image from
the page next we will set the canvas width and height to be the same as image
and put the image on it using drawImage method from the canvas 2d context
next we will create another image object to be used as an output we will try to
export current canvas image to be able to see the result just use toDataURL
method from the canvas object and set it as output image source then set the size
and append it to the body if it works correctly you will see a smaller image
as I reduce the width to 600 pixels now let's work on a pixelating process first
we will get the pixels array using get image data then we'll set the sample
size to define how much pixelated effect would be the larger sample the largest
square size so let's set it to 40 pixels next we are going to loop through the
pixels array but first we need to understand the structure the array has
only single dimension so it starts with the first pixel of the first row
followed by the next pixels in the same row then start over with the next row
repeatedly until the end now each pixel has 4 datas the first three is RGB value
and the last one is alpha or transparency so the array size will be 4
times of the number of pixels okay let's create a loop we will increase the
count by the sample size
then we will get a pixel index position don't forget to multiply it by
four then we'll take the RGB and alpha data from the first pixel in a sample
size to represent the entire square and then painting on canvas
and here's the result you can increase the square size by adjusting the sample
size and that's all for this tutorial if you love this video and want to see more
development tips and tutorials don't forget to subscribe to this channel to
stay tuned for weekly update thanks watching see you next time bye