Answer the question
In order to leave comments, you need to log in
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
The error is that when drawing each cell, you erase the ENTIRE canvas:
ctx.clearRect(0 , 0 , ctx.canvas.width , ctx.canvas.height)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question