Anargu Anargu - 19 days ago 4
HTML Question

How is possible this Gaussian Blur javascript algorithm work?

I found the following script to do a blur image processing to an image since javascript. I replicated the sample but I didn't understand how a little part of this script could work fine, I will show the script:

var gaussianBlur = function() {
var data = ctx.getImageData(0,0,canvas.width,canvas.height);
var px =;
var tmpPx = new Uint8ClampedArray(px.length);

for (var i = 0, len= px.length; i < len; i++) {
if (i % 4 === 3) {continue;}

px[i] = ( tmpPx[i]
+ (tmpPx[i - 4] || tmpPx[i])
+ (tmpPx[i + 4] || tmpPx[i])
+ (tmpPx[i - 4 * data.width] || tmpPx[i])
+ (tmpPx[i + 4 * data.width] || tmpPx[i])
+ (tmpPx[i - 4 * data.width - 4] || tmpPx[i])
+ (tmpPx[i + 4 * data.width + 4] || tmpPx[i])
+ (tmpPx[i + 4 * data.width - 4] || tmpPx[i])
+ (tmpPx[i - 4 * data.width + 4] || tmpPx[i])
// = px;

delete tmpPx;
btnBlur.textContent = 'Blur'; }

This function (
) is triggered to a html button, so when it's clicked, it will process the image to get it blurred and this process will be repeated according to the number of clicks on the button. The part of the code I don't understand is when it finishes the for loop, all the math operations were saved on the
variable but in the next line code
, this
variable doesn't take the new changed variable
. So I wonder, how is it possible that the canvas could render with the image blurred if
variable wasn't changed its
component (because = px
as shown in the first lines of

In my opinion, to understand this code, I would put a = px;
after the for loop, with this line code I am saying that the new
will be set on
variable. And with ot without this line code the algorithm works. So I am confused why it works despite
is not set by the new
value. Please help me to understand it.

Thanks in advance


What is happening, is that px is in reality the same object as, meaning that every changes in px take effect in the object you would think is just a copy. Look at this simple example:

// we create an object 'x' with an array of data
var x = {
    data :[ 0, 1]

// Assign value to 'p'
var p =;
console.log(p); // [0, 1]
// Then we change one of the array's values to 'Xpto'
p[1] = "Xpto";
// Now look what happened to
console.log(; //[0, "Xpto"]

This is why your code is working. px is not a copy, it is a reference.