ctx.clearRect() not clearing the screen?

Question: I’m making an io game and i’m trying to draw players to the screen. The problem is that ctx.clearRect() isn’t working… I’ve tried putting it after ctx.fill() but then nothing shows up on the screen. How do I fix this?

Repl link: https://replit.com/@ColoredHue/BulletPartyio

function spawnGame() {
        move = true
        setTimeout(function() {
                //Draw a player rectangle at x,y
                function drawPlayer(player, playerId) {
                        console.log(player, playerId)
                        if (Object.keys(gamestate[LobbyId])[0] == playerId) {
                                ctx.fillStyle = "red";
                        } else if (Object.keys(gamestate[LobbyId])[1] == playerId) {
                                ctx.fillStyle = "yellow";
                        } else if (Object.keys(gamestate[LobbyId])[1] == playerId) {
                                ctx.fillStyle = "green";
                        } else if (Object.keys(gamestate[LobbyId])[3] == playerId) {
                                ctx.fillStyle = "blue";
                        ctx.clearRect(0, 0, canvas.width, canvas.height)
                        ctx.rect(player.x, player.y, 25, 25);
                        //draw the players that the server sent
                for (let player in gamestate[LobbyId]) {
                        drawPlayer(gamestate[LobbyId][player], player)
        }, 1000/60);

It’s because you’re calling that clearRect and then making a new rect right after, but you’re doing that on repeat in a loop. So you’re basically rendering it 60 fps i think, which sounds like what you’re trying to do. So what is the problem with it not clearing? It’s because you’re clearing the canvas, then putting something on it. Then clearing it, then putting the same thing on it. So to you, it appears that clearRect is not working.

1 Like

I’m pretty sure clear rect isn’t working because isn’t it supposed to get rid of the old players when working?

It would probably help if I showed you:

When the player moves I don’t want it to make a line, It should appear as if the box is actually moving.

There are two main issues:

First of all, you are clearing the screen every time you draw a new player, so you will only see only player. You should probably move clearRect to the line above the for loop, but not inside thedrawPlayer function.

Secondly, you aren’t using rect correctly, rect should be used inside of a path:

ctx.rect(x, y, width, height);

Instead, you probably just want to use fillRect (which essentially just does the above):

ctx.fillRect(x, y, width, height);

I tested these changes in a fork and everything seemed to work as you would expect :smile:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.