'JavaScript canvas tilemap rendering
I try to render tilemap using canvas but it appears only when I resize the window. When I refresh the page I see only a black screen but when resize window tilemap was rendered.
Backend:
socket.emit('server:tileMap', { tilemap, tileTypes });
Frontend:
socket.on('server:tileMap', ({ tilemap, tileTypes}) => {
drawTilemap(tilemap, tileTypes)
});
let tilemapData = {};
window.addEventListener('resize', () => {
resizeCanvas();
drawTilemap(tilemapData.tilemap, tilemapData.tileTypes);
drawBuildingTilemap(tilemapData.buildingData);
});
const drawTilemap = (tilemap, tileTypes) => {
tilemapData['tilemap'] = tilemap;
tilemapData['tileTypes'] = tileTypes;
resizeCanvas();
let x = 0, y = 0;
for (const row of tilemap) {
for (const el of row) {
for (const type of tileTypes) {
if (type[0] === el) {
const mapCanvas = $('#map-ctx');
const ctx = mapCanvas.getContext('2d', { alpha: false });
const img = new Image();
img.src = `/sprites/${type[1]}.png`;
ctx.drawImage(img, x, y, 32, 32);
}
}
x += 32;
}
x = 0;
y += 32;
}
}
const resizeCanvas = () => {
const map = $('.my-city');
allCanvases.forEach(canvas => {
canvas.height = map.offsetHeight;
canvas.width = map.offsetWidth;
})
Pug file
canvas#map-ctx
canvas#building-ctx
canvas#marked-ctx
include ../components/chunkInfo.pug
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
