M
M
MANCHERA CHAN2021-08-07 11:32:55
JavaScript
MANCHERA CHAN, 2021-08-07 11:32:55

I can't draw a map from a 2D array. How to draw it on canvas?

Code not working

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');


// global info
let GI = {
    // tiles size
    TS: 50,
}

let map = [
    [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
    [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
    [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
    [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
    [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
    [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
    [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
    [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
    [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
    [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
]

function SetCanvasSize(e){
    ctx.canvas.width = e.innerWidth
    ctx.canvas.height = e.innerHeight
}

function drowMap(){
    for(let x = 0; x < map.length; x++){
        for(let y = 0; y < map[x].length; y++){
            ctx.clearRect(0 , 0 , ctx.canvas.width , ctx.canvas.height)

            ctx.fillStyle = '#ff0000'
            ctx.fillRect(x * GI.TS , y * GI.TS , GI.TS , GI.TS)
            
        }
    }
}

drowMap()

SetCanvasSize(window)

window.addEventListener('resize' , ()=>{
    drowMap()
    
    SetCanvasSize(window)
})

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2021-08-07
@MANCHERA

First resize, then draw.

S
Sergey Sokolov, 2021-08-07
@sergiks

The error is that when drawing each cell, you erase the ENTIRE canvas:

ctx.clearRect(0 , 0 , ctx.canvas.width , ctx.canvas.height)

Working example :

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question