The first thing i did was call clearRect. Then, I set the order for when each image should load with an array. I was expecting the 2d town I made to be set in a void but clearRect coloured black over everything. My best guess is that clearRect executes at a different time since it is not in an array. hence pasting over everything. Is the best solution just popping an all black image into the array first?
//index elements
let element = document.querySelector('#game-cont')
let canvas= element.querySelector('#game-canvas')
let ctx = canvas.getContext("2d")
//variables
let maparray = []
let x=162
let y=90
let mapX=0
let mapY=0
let spd =1
let rectPx=18
ctx.imageSmoothingEnabled=false
class gameobject{
constructor(pic,cutstartX, cutstartY, cutendX, cutendY, x, y, scalex, scaley, name){
this.pic = pic;
this.cutstartX=cutstartX;
this.cutstartY=cutstartY;
this.cutendX=cutendX;
this.cutendY=cutendY;
this.x=x;
this.y=y;
this.scalex=scalex;
this.scaley=scaley;
this.name=name+""
maparray.push(this)
}
static drawAll(){
//PROBLEM=> ctx.clearRect(0,0,canvas.width,canvas.height)
maparray.forEach( (item)=>{
const obj= new Image()
obj.onload= ()=> {
ctx.drawImage(
obj,
item.cutstartX,
item.cutstartY,
item.cutendX,
item.cutendY,
item.x,
item.y,
item.scalex,
item.scaley)
}
obj.src =item.pic
}
)
}
}
function moveall(char,num){
this.char=char
this.num=num
if (char=="y"){
for (let r=0; r!=(3);r++){
maparray[r].y += num
}
} else if (char=="x"){
for (let r=0; r!=(3);r++){
maparray[r].x += num
}
}
}
//game objects
let back = new gameobject('/hrr-map.png', 0, 0, 100, 100, mapX, mapY, 1800, 1800,"backtown")
let paper1 = new gameobject('/ppr.png', 0, 0, 100, 100, 60, 10, 100, 100,"paper1")
let paper2 = new gameobject('/ppr.png', 0, 0, 100, 100, 65, 0, 100, 100,"paper1")
let hero2 = new gameobject('/beastman2.jpg', 0, 0, 194, 259, x, y, rectPx, rectPx,"hero2")
// controls
let dir
document.addEventListener("keydown",e =>{
dir=e.key
})
document.addEventListener("keyup",e =>{
dir='null'
})
function mover(){
if (dir=='w'){
moveall("y",spd)
}if (dir=='s'){
moveall("y",(-spd))
} else if (dir=='a'){
moveall("x",spd)
} else if (dir=='d'){
moveall("x",(-spd))
}}
//animations
function update(){
mover()
gameobject.drawAll()
requestAnimationFrame(update)
}
requestAnimationFrame(update)