Why does clearRect delete everything? [closed]

2 weeks ago 22
ARTICLE AD BOX

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 x=162 let y=90 ctx.imageSmoothingEnabled=false const hero2= new Image() function drawAll(){ //PROBLEM=> ctx.clearRect(0,0,canvas.width,canvas.height) hero2.onload= ()=> { ctx.drawImage( hero2, 0, 0, 194, 259, x, y, 18, 18) } hero2.src ='/beastman2.jpg' } // controls let dir document.addEventListener("keydown",e =>{ dir=e.key }) document.addEventListener("keyup",e =>{ dir='null' }) function mover(){ if (dir=='w'){ y-- }if (dir=='s'){ y++ } else if (dir=='a'){ x-- } else if (dir=='d'){ x++ }} //animations function update(){ mover() drawAll() requestAnimationFrame(update) } window.onload= requestAnimationFrame(update) *{ box-sizing: border-box; } body{ background-color: black; padding: 0; margin: 0; overflow: hidden; } #game-cont{ position: relative; width: 352px; height: 198px; margin: 0 auto; margin-top: 30px; outline: 1px solid floralwhite; transform: scale(2) translateY(50%); } #game-cont canvas{ image-rendering:pixelated; } <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>title</title> <link rel="stylesheet" href="/index.css" type="text/css"> </head> <body> <div id="game-cont"> <canvas id="game-canvas" width="352" height="198"></canvas> </div> <script src="/gameobject.js"> </script> </body> </html>
Read Entire Article