Wrapped Tile Map Test
by nickcoutsos
HTML
<body>
<canvas></canvas>
</body>
CSS
html,
body {
width: 100vw;
height: 100vh;
padding: 0;
margin: 0;
}
canvas {
display: block;
padding: 0;
margin: 0;
}
JavaScript
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
const WIDTH = canvas.width = Math.floor(document.body.clientWidth)
const HEIGHT = canvas.height = Math.floor(document.body.clientHeight)
const TILE_SIZE = 20
const VIEWER_SIZE = 100
const VIEWER_TILES = VIEWER_SIZE / TILE_SIZE
const COLUMNS = WIDTH / VIEWER_SIZE
const ROWS = HEIGHT / VIEWER_SIZE
const tiles = []
for (let r = 0; r < VIEWER_TILES; r++) {
for (let c = 0; c < VIEWER_TILES; c++) {
const i = (r * VIEWER_TILES) + c
tiles.push({
index: i,
col: c,
row: r,
hue: 240 * i / (Math.pow(VIEWER_TILES, 2) - 1)
})
}
}
function drawGrid () {
ctx.strokeStyle = 'gray'
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLUMNS; c++) {
ctx.strokeRect(
c * VIEWER_SIZE,
r * VIEWER_SIZE,
VIEWER_SIZE,
VIEWER_SIZE
)
}
}
}
function drawTiles (x, y) {
// row/col number of cell containing the viewer box's top-left corner
const viewCol = Math.floor(x / VIEWER_SIZE)
const viewRow = Math.floor(y / VIEWER_SIZE)
// row/col number of the tile containining (x, y)
const tileCol = Math.floor(x / TILE_SIZE)
const tileRow = Math.floor(y / TILE_SIZE)
const tileX = tileCol * TILE_SIZE
const tileY = tileRow * TILE_SIZE
for (let r = 0; r < VIEWER_TILES + 1; r++) {
for (let c = 0; c < VIEWER_TILES + 1; c++) {
let col = (tileCol + c) % VIEWER_TILES
let row = (tileRow + r) % VIEWER_TILES
let i = (row * VIEWER_TILES) + col
if (i < 0) {
continue
}
ctx.fillStyle = `hsla(${tiles[i].hue}, 100%, 50%, .4)`
ctx.fillRect(
(tileCol + c) * TILE_SIZE,
(tileRow + r) * TILE_SIZE,
TILE_SIZE,
TILE_SIZE
)
}
}
}
function update ({ clientX: x = 0, clientY: y = 0 } = {}) {
ctx.fillStyle = 'hsl(210, 20%, 20%)'
ctx.fillRect(0, 0, WIDTH, HEIGHT)
drawGrid()
ctx.strokeStyle = 'teal'
ctx.strokeRect(
x - VIEWER_SIZE/2,
...