From dfdadd6f7953f7322aef892e73ea058708dac7c5 Mon Sep 17 00:00:00 2001 From: HF Date: Fri, 18 Jun 2021 11:21:28 +0200 Subject: [PATCH] fix color picker in privacy browsers blocking canvas stuff --- src/core/Palette.js | 36 +++++++++++++++++++++++++++++++++++- src/ui/ChunkRGB.js | 2 +- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/core/Palette.js b/src/core/Palette.js index 04b6f00..68a76c8 100644 --- a/src/core/Palette.js +++ b/src/core/Palette.js @@ -56,7 +56,11 @@ class Palette { * @param b b * @return index of color */ - getIndexOfColor(r: number, g: number, b: number): ColorIndex { + getIndexOfColor( + r: number, + g: number, + b: number, + ): ColorIndex { const { rgb } = this; let i = rgb.length / 3; while (i > 0) { @@ -72,6 +76,36 @@ class Palette { return null; } + /* + * Get closest matching color index of RGB color + * @param r r + * @param g g + * @param b b + * @return index of color + */ + getClosestIndexOfColor( + r: number, + g: number, + b: number, + ): ColorIndex { + const { rgb } = this; + let i = rgb.length / 3; + let closestIndex = 0; + let closestDistance = null; + while (i > 0) { + i -= 1; + const off = i * 3; + let distance = (rgb[off] - r) ** 2; + distance += (rgb[off + 1] - g) ** 2; + distance += (rgb[off + 2] - b) ** 2; + if (closestDistance === null || closestDistance > distance) { + closestIndex = i; + closestDistance = distance; + } + } + return closestIndex; + } + /* * Take a buffer of indexed pixels and output it as ABGR Array * @param chunkBuffer Buffer of indexed pixels diff --git a/src/ui/ChunkRGB.js b/src/ui/ChunkRGB.js index 7450d9d..cb24b5a 100644 --- a/src/ui/ChunkRGB.js +++ b/src/ui/ChunkRGB.js @@ -88,7 +88,7 @@ class ChunkRGB { const ctx = this.image.getContext('2d'); const rgb = ctx.getImageData(x, y, 1, 1).data; - return this.palette.getIndexOfColor(rgb[0], rgb[1], rgb[2]); + return this.palette.getClosestIndexOfColor(rgb[0], rgb[1], rgb[2]); } hasColorIn(cell: Cell, color: ColorIndex): boolean {