kennethcachia / background-check

Automatically switch to a darker or a lighter version of an element depending on the brightness of images behind it.
http://kennethcachia.com/background-check/
MIT License
3.27k stars 282 forks source link

Ignore brightness of pixels outside the viewport #119

Open DanActions opened 2 years ago

DanActions commented 2 years ago

Fixes #57 by ignoring pixels outside of the viewport when calculating brightness.

I think the issue is in calculatePixelBrightness(). The following lines get the dimensions of the target image and fetch those pixels from the canvas:

var dims = target.getBoundingClientRect();
...
data = context.getImageData(dims.left, dims.top, dims.width, dims.height).data;

The function then loops through data pixel-by-pixel to calculate the average brightness.

The problem is that if part of the bounding rectangle is outside the viewport, getImageData will return rgba(0,0,0,0) for those pixels. The formula that calculatePixelBrightness() uses to calculate average brightness doesn't consider the alpha value, causing it to see these pixels as black, thus skewing the calculated brightness to be much darker than the visible image.

The pull request attempts to fix this by trimming off the parts of the bounding rectangle that are outside the viewport before calling getImageData.