Anargu Anargu - 1 month ago 17
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 = data.data;
var tmpPx = new Uint8ClampedArray(px.length);
tmpPx.set(px);

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])
)/9;
};
// data.data = px;

ctx.putImageData(data,0,0);
delete tmpPx;
btnBlur.removeAttribute('disabled');
btnBlur.textContent = 'Blur'; }


This function (
gaussianBlur()
) 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
px
variable but in the next line code
ctx.putImageData(data,0,0);
, this
data
variable doesn't take the new changed variable
px
. So I wonder, how is it possible that the canvas could render with the image blurred if
data
variable wasn't changed its
data
component (because
data.data = px
as shown in the first lines of
gaussianBlur
function).

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

Thanks in advance

Answer

What is happening, is that px is in reality the same object as data.data, 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 x.data value to 'p'
var p = x.data;
console.log(p); // [0, 1]
// Then we change one of the array's values to 'Xpto'
p[1] = "Xpto";
// Now look what happened to x.data
console.log(x.data); //[0, "Xpto"]

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