# Rectangles clear each other when moving on canvas

I am having this problem after moving rectangles, they seem to delete one another. Most probably it is a problem with clearRect(...) method. This is the clean function I am using:

clean: function(element){
// All default values clean all the screen
if(typeof element.x === 'undefined'){
element.x = 0;
}

if(typeof element.y === 'undefined'){
element.y = 0;
}

if(typeof element.width === 'undefined'){
element.width = canvas.width;
}

if(typeof element.height === 'undefined'){
element.height = canvas.height;
}

// In case values are entered
if(element.type === 'rectangle'){
ctx.clearRect(element.x,element.y,element.width,element.height);
}
}


This is the rendering

rect: function(element){
// Check if color is defined
if(typeof element.color === 'undefined'){
element.color = 'black';
}
else{
ctx.fillStyle = element.color;
}

// Draw the rectangle
ctx.fillRect(element.x,element.y,element.width,element.height);
}


Clearing the screen is only one half of the puzzle. I'm going to bet you also only re-draw the rectangles if/when they move. To confirm, you could make the red cube continue to move across the screen, I would expect there to be no graphical glitches.

The solution: Draw everything (on screen) every frame. There are fancier ways to deal with this, but they are not necessary for most, if not all, projects.

• Yeah, exactly. Just noticed that. It doesn't clear the red one. Also, I did not want to draw everything since it needs more processing and the squares are redrawn without moving. I do not know if this is ok though. – GSquadron May 7 '15 at 19:32
• It seems inefficient to draw everything all the time, but graphics cards are really good at what they do and most per-processing that we think is speeding things up is actually just getting in the GPU's way. I don't know enough about it to describe it well, but I know that GPUs to a lot of optimizing to figure out how to efficiently draw the given scene. Basically: you just just draw everything (on screen) all the time. – John McDonald May 7 '15 at 19:44
• Please note: You shouldn't draw EVERYTHING. Only draw things in view, this is important. If you have a huge tilemap and decide to draw everything, you will pay. – Vaughan Hilts May 7 '15 at 19:47
• Thanks, I mentioned that in my comment, but I have updated my answer – John McDonald May 7 '15 at 19:54
• @JohnMcDonald Sorry, should have read the comments. :) PS: Disappointed to see you got rid of Asteroid Outpost. :( – Vaughan Hilts May 7 '15 at 19:55