1

I'm developing a basic Zelda-like game (NES) to improve my coding skills. In the first implementation, you can move around. The only thing is that whenever you do move, it just draws a line. I know that I need to clear the canvas and have it redrawn to update the frame, but I can't figure out how to get it to clear. I use a canvas for the game screen.

I've tried using clearRect() and fillstyle/fillRect. clearRect didn't do anything at all and fillRect gave me the error:

"Uncaught ReferenceError: rgba is not defined at c_ui.update"

this is the relevant code:

draw(){
    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");
    ctx.moveTo(this.hero.position.x,this.hero.position.y);
    ctx.lineTo(this.hero.position.x + 10, this.hero.position.y);
    ctx.lineTo(this.hero.position.x + 10, this.hero.position.y + 10);
    ctx.lineTo(this.hero.position.x, this.hero.position.y + 10);
    ctx.lineTo(this.hero.position.x,this.hero.position.y);
    ctx.stroke();
    console.log(this.hero.position.x, this.hero.position.y)
}

update(){
    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");
    ctx.fillstyle = rgba(225, 225, 225, 0);
    ctx.fillRect(0, 0, c.width, c.height);  
    console.log("cleared screen");
}

ui = new c_ui;
ui.draw();
addEventListener('keydown',function(move){
    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");
    if (move.code == "KeyD" || move.code == "ArrowRight" ){
        ui.hero.position.x = ui.hero.position.x + 1;
    ui.update();
    ui.draw();
});
Sybille Peters
  • 2,832
  • 1
  • 27
  • 49
  • You need to write **ctx.beginPath()** just above where you draw the lines. The JavaScript context needs this otherwise it will keep drawing the *old* line like it’s doing now. Hope this helps. – Joachim Mar 04 '23 at 17:25
  • Yes it did! I got an error from rgba, but a new error this time so i tried clearRect again and it works the way I want it to. Thanks for the help – Spelunkhead Mar 04 '23 at 19:02
  • No problem! I often forget about the *beginPath()* function when developing. It never hurts to have a reminder every now and then :) – Joachim Mar 04 '23 at 20:55

0 Answers0