Refactored map grid lightness function

This commit is contained in:
Mitchell McCaffrey 2020-07-13 17:44:22 +10:00
parent d3b0ec6446
commit 3afae404d7
2 changed files with 37 additions and 34 deletions

View File

@ -8,8 +8,7 @@ import useDataSource from "../../helpers/useDataSource";
import { mapSources as defaultMapSources } from "../../maps";
import { getStrokeWidth } from "../../helpers/drawing";
const lightnessDetectionOffset = 0.1;
import { getImageLightness } from "../../helpers/image";
function MapGrid({ map, gridSize }) {
const mapSource = useDataSource(map, defaultMapSources);
@ -28,38 +27,7 @@ function MapGrid({ map, gridSize }) {
// When the map changes find the average lightness of its pixels
useEffect(() => {
if (mapLoadingStatus === "loaded") {
const imageWidth = mapImage.width;
const imageHeight = mapImage.height;
let canvas = document.createElement("canvas");
canvas.width = imageWidth;
canvas.height = imageHeight;
let context = canvas.getContext("2d");
context.drawImage(mapImage, 0, 0);
const imageData = context.getImageData(0, 0, imageWidth, imageHeight);
const data = imageData.data;
let lightPixels = 0;
let darkPixels = 0;
// Loop over every pixels rgba values
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
const max = Math.max(Math.max(r, g), b);
if (max < 128) {
darkPixels++;
} else {
lightPixels++;
}
}
const norm = (lightPixels - darkPixels) / (imageWidth * imageHeight);
if (norm + lightnessDetectionOffset < 0) {
setIsImageLight(false);
} else {
setIsImageLight(true);
}
setIsImageLight(getImageLightness(mapImage));
}
}, [mapImage, mapLoadingStatus]);

35
src/helpers/image.js Normal file
View File

@ -0,0 +1,35 @@
const lightnessDetectionOffset = 0.1;
/**
* @returns {boolean} True is the image is light
*/
export function getImageLightness(image) {
const imageWidth = image.width;
const imageHeight = image.height;
let canvas = document.createElement("canvas");
canvas.width = imageWidth;
canvas.height = imageHeight;
let context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
const imageData = context.getImageData(0, 0, imageWidth, imageHeight);
const data = imageData.data;
let lightPixels = 0;
let darkPixels = 0;
// Loop over every pixels rgba values
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
const max = Math.max(Math.max(r, g), b);
if (max < 128) {
darkPixels++;
} else {
lightPixels++;
}
}
const norm = (lightPixels - darkPixels) / (imageWidth * imageHeight);
return norm + lightnessDetectionOffset >= 0;
}