added basic matrix simulation

This commit is contained in:
waltem01 2023-11-24 10:22:46 +01:00
parent 6c93cbe2b0
commit 187c87e6d2

View File

@ -3,6 +3,12 @@
success: boolean;
}
interface MatrixCell {
xIndex: number;
yIndex: number;
color: string;
}
async function get(event: SubmitEvent) {
const form = event.target as HTMLFormElement;
@ -17,6 +23,12 @@
const form = event.target as HTMLFormElement;
const fdata = new FormData(form);
switch (form.dataset.endpoint) {
case 'color':
colorSelect(fdata);
break;
}
const response = await fetch(`http://localhost:8080/${form.dataset.endpoint}`, {
method: form.method,
mode: 'cors',
@ -25,9 +37,35 @@
const mdata = (await response.json()) as MatrixResponse;
alert(mdata.success ? 'Success!' : 'Error!');
}
function colorSelect(formData: FormData) {
pixelColor[0] = parseInt((formData.get('r') as string) ?? '255');
pixelColor[1] = parseInt((formData.get('g') as string) ?? '255');
pixelColor[2] = parseInt((formData.get('b') as string) ?? '255');
}
function setColor(event: MouseEvent) {
if (!mousePressed) return;
const toHex = pixelColor.map((e) => e.toString(16).padStart(2, '0'));
const colStr = toHex.join('');
const parent = event.target as HTMLTableCellElement;
const x = parseInt(parent.dataset.x ?? '0');
const y = parseInt(parent.parentElement?.dataset.y ?? '0');
matrix[y][x].color = colStr;
}
const matrix = Array.from({ length: 192 }, (_, yIndex) =>
Array.from({ length: 192 }, (_, xIndex) => ({ xIndex, yIndex, color: '000000' }) as MatrixCell)
) as MatrixCell[][];
const pixelColor = [255, 255, 255];
let mousePressed = false;
</script>
<h1 class="text-4xl font-bold mb-5">RGB LED Matrix</h1>
<h1 class="text-4xl font-bold m-5 text-center">RGB LED Matrix</h1>
<div class="grid grid-rows-7 p-1">
<form class="grid grid-cols-2" method="GET" data-endpoint="update" on:submit|preventDefault={get}>
<label class="border-2 border-black border-r-0 border-b-0 pl-1" for="update">Update:</label>
@ -287,3 +325,24 @@
/>
</form>
</div>
<div class="flex justify-center">
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<table
class="mt-5"
on:mousedown|preventDefault={() => (mousePressed = true)}
on:mouseup|preventDefault={() => (mousePressed = false)}
>
{#each matrix as row}
<tr data-y={row[0].yIndex}>
{#each row as cell}
<td
data-x={cell.xIndex}
class="p-0.75"
style="background-color: #{cell.color}"
on:mouseenter={setColor}
/>
{/each}
</tr>
{/each}
</table>
</div>