From 44b66c37fc6fe3bf0a7ef68a42410b25aba9e98a Mon Sep 17 00:00:00 2001 From: Vinzenz Schroeter Date: Sun, 14 Apr 2024 13:23:04 +0200 Subject: [PATCH] random color on launch, dynamic map color --- tank-frontend/src/ClientScreen.tsx | 18 ++++++++++++++---- tank-frontend/src/index.tsx | 16 ++++++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/tank-frontend/src/ClientScreen.tsx b/tank-frontend/src/ClientScreen.tsx index 589a1e3..9e774a7 100644 --- a/tank-frontend/src/ClientScreen.tsx +++ b/tank-frontend/src/ClientScreen.tsx @@ -5,9 +5,6 @@ import './ClientScreen.css'; const pixelsPerRow = 352; const pixelsPerCol = 160; -const onColor = [0, 180, 0, 255]; -const offColor = [0, 0, 0, 255]; - function getIndexes(bitIndex: number) { return { byteIndex: Math.floor(bitIndex / 8), @@ -15,11 +12,24 @@ function getIndexes(bitIndex: number) { }; } +// @ts-ignore +const rootElement = document.querySelector(':root')!; + +function normalizeColor(context: CanvasRenderingContext2D, color: string) { + context.fillStyle = color; + context.fillRect(0, 0, 1, 1); + return context.getImageData(0, 0, 1, 1).data; +} + function drawPixelsToCanvas(pixels: Uint8Array, canvas: HTMLCanvasElement) { const drawContext = canvas.getContext('2d'); if (!drawContext) throw new Error('could not get draw context'); + const rootStyle = getComputedStyle(rootElement); + const colorPrimary = normalizeColor(drawContext, rootStyle.getPropertyValue('--color-primary')); + const colorBackground = normalizeColor(drawContext, rootStyle.getPropertyValue('--color-background')); + const imageData = drawContext.getImageData(0, 0, canvas.width, canvas.height, {colorSpace: 'srgb'}); const data = imageData.data; @@ -30,7 +40,7 @@ function drawPixelsToCanvas(pixels: Uint8Array, canvas: HTMLCanvasElement) { const {byteIndex, bitInByteIndex} = getIndexes(pixelIndex); const mask = (1 << bitInByteIndex); const isOn = (pixels[byteIndex] & mask) !== 0; - const color = isOn ? onColor : offColor; + const color = isOn ? colorPrimary : colorBackground; for (let colorChannel of [0, 1, 2, 3]) data[pixelIndex * 4 + colorChannel] = color[colorChannel]; diff --git a/tank-frontend/src/index.tsx b/tank-frontend/src/index.tsx index 07bbf93..cde0723 100644 --- a/tank-frontend/src/index.tsx +++ b/tank-frontend/src/index.tsx @@ -3,6 +3,22 @@ import {createRoot} from 'react-dom/client'; import './index.css'; import App from "./App.tsx"; +function getRandomColor() { + const letters = '0123456789ABCDEF'; + let color = '#'; + for (let i = 0; i < 3; i++) { + color += letters[Math.floor(Math.random() * letters.length)]; + } + return color; +} + +// @ts-ignore +const rootStyle = document.querySelector(':root')?.style; +if (rootStyle) { + rootStyle.setProperty('--color-primary', getRandomColor()); + rootStyle.setProperty('--color-secondary', getRandomColor()); + rootStyle.setProperty('--color-background', getRandomColor()); +} createRoot(document.getElementById('root')!).render(