Draw a grid on a canvas
A world often gives a grid (a board, a map, a picture made of pixels) as an array of rows of numbers. Draw it on a <canvas> with one square per cell and one colour per value and draw it again only when the world gives a new grid. In the example the beach gives a new board twice a second.
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;
}
});How it works
- A grid in
datais an array of rows read asboard[row][column]. It hasboard.lengthrows ofboard[0].lengthcells. drawGridgives each cell a square whose side isSIZEdivided by the larger of the two counts. Leaving the last pixel of each square empty draws a thin line between the cells.COLORSmaps each value to its colour.- A grid that changed arrives as a new array and a grid that did not change stays the same array. A plain
!==then recognises a new grid. The React effect depends on[board]and the plain JavaScript version comparesboard !== drawnBoard. - A screen reader gets no text from a canvas. Like the caption of the example, write what matters as text next to the canvas.
See also
- Grid: a grid component that reports clicks on its cells.
- Show a picture from data.
- The data of the world.