background-check icon indicating copy to clipboard operation
background-check copied to clipboard

Ignore brightness of pixels outside the viewport

Open DanActions opened this issue 3 years ago • 0 comments

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.

DanActions avatar Feb 23 '22 21:02 DanActions