Skip to content

Disegna una griglia su un canvas ​

Spesso un mondo dà una griglia (una scacchiera, una mappa, un'immagine fatta di pixel) come array di righe di numeri. Disegnala su un <canvas> con un quadrato per cella e un colore per valore e ridisegnala solo quando il mondo dà una griglia nuova. Nell'esempio la spiaggia dà una nuova griglia due volte al secondo.

jsx
import { useEffect, useRef } from 'react';
import { useWorld } from './useWorld.js';

// The board of the fake world has 10 rows of 10 cells, each 0 (empty), 1 (water) or 2 (sand), and moves with time.
function boardAt(time) {
	const step = Math.floor(time / 500);
	return Array.from({ length: 10 }, (_, row) => Array.from({ length: 10 }, (_, column) => {
		if ((row + column + step) % 6 === 0) return 1;
		return (row * 3 + column + step) % 11 === 0 ? 2 : 0;
	}));
}

// The fake beach gives a new board every 500 ms.
const beach = {
	name: 'Beach',
	data: { board: { every: 500, value: boardAt } },
};

const COLORS = ['#eeeeee', '#3d7ab8', '#f2cf3a']; // one color per cell value
const SIZE = 240; // the canvas, in pixels

// Draws a grid (an array of rows) on a canvas, one square per cell.
function drawGrid(canvas, grid) {
	const context = canvas.getContext('2d');
	const cell = SIZE / Math.max(grid.length, grid[0].length);
	context.clearRect(0, 0, SIZE, SIZE);
	grid.forEach((row, rowIndex) => row.forEach((value, columnIndex) => {
		context.fillStyle = COLORS[value] ?? '#000000';
		// One pixel less than the cell leaves a thin line between the cells.
		context.fillRect(columnIndex * cell, rowIndex * cell, cell - 1, cell - 1);
	}));
}

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: beach } });
	const canvas = useRef(null);
	const board = world?.data.board;

	// Draw again only when the board is a new one.
	useEffect(() => {
		if (board && canvas.current) drawGrid(canvas.current, board);
	}, [board]);

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			<h2>{world.name}</h2>
			<canvas ref={canvas} width={SIZE} height={SIZE} />
			<p>{board ? `${board.length} × ${board[0].length} board` : 'Waiting for the board…'}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The board of the fake world has 10 rows of 10 cells, each 0 (empty), 1 (water) or 2 (sand), and moves with time.
function boardAt(time) {
	const step = Math.floor(time / 500);
	return Array.from({ length: 10 }, (_, row) => Array.from({ length: 10 }, (_, column) => {
		if ((row + column + step) % 6 === 0) return 1;
		return (row * 3 + column + step) % 11 === 0 ? 2 : 0;
	}));
}

// The fake beach gives a new board every 500 ms.
const beach = {
	name: 'Beach',
	data: { board: { every: 500, value: boardAt } },
};

const COLORS = ['#eeeeee', '#3d7ab8', '#f2cf3a']; // one color per cell value
const SIZE = 240; // the canvas, in pixels

// Draws a grid (an array of rows) on a canvas, one square per cell.
function drawGrid(canvas, grid) {
	const context = canvas.getContext('2d');
	const cell = SIZE / Math.max(grid.length, grid[0].length);
	context.clearRect(0, 0, SIZE, SIZE);
	grid.forEach((row, rowIndex) => row.forEach((value, columnIndex) => {
		context.fillStyle = COLORS[value] ?? '#000000';
		// One pixel less than the cell leaves a thin line between the cells.
		context.fillRect(columnIndex * cell, rowIndex * cell, cell - 1, cell - 1);
	}));
}

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: beach } });

const title = document.createElement('h2');
const canvas = document.createElement('canvas');
canvas.width = SIZE;
canvas.height = SIZE;
const caption = document.createElement('p');
document.body.append(title, canvas, caption);

let drawnBoard = null;
world.subscribe((node) => {
	title.textContent = node.name;
	const board = node.data.board;
	caption.textContent = board ? `${board.length} × ${board[0].length} board` : 'Waiting for the board…';
	// Draw again only when the board is a new one.
	if (board && board !== drawnBoard) {
		drawGrid(canvas, board);
		drawnBoard = board;
	}
});
Live, on a fake world
Open

Come funziona ​

  • Una griglia in data è un array di righe che si legge come board[row][column] e ha board.length righe di board[0].length celle.
  • drawGrid dà a ogni cella un quadrato il cui lato è SIZE diviso per il maggiore dei due conteggi. Lasciare vuoto l'ultimo pixel di ogni quadrato disegna una linea sottile fra le celle. COLORS associa a ogni valore il suo colore.
  • Una griglia cambiata arriva come array nuovo e una griglia rimasta uguale resta lo stesso array. Per riconoscere una griglia nuova basta allora un semplice !==. L'effetto di React dipende da [board] e la versione in JavaScript semplice confronta board !== drawnBoard.
  • Uno screen reader non ricava alcun testo da un canvas. Come fa la didascalia dell'esempio, scrivi accanto al canvas in forma di testo quello che conta.

Vedi anche ​

Il GUI kit di UNaIVERSE, rilasciato con licenza Apache 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.