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'){

This is the rendering

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

    // Draw the rectangle

The problem


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.

  • \$\begingroup\$ 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. \$\endgroup\$
    – GSquadron
    May 7 '15 at 19:32
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ May 7 '15 at 19:44
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ May 7 '15 at 19:47
  • \$\begingroup\$ Thanks, I mentioned that in my comment, but I have updated my answer \$\endgroup\$ May 7 '15 at 19:54
  • \$\begingroup\$ @JohnMcDonald Sorry, should have read the comments. :) PS: Disappointed to see you got rid of Asteroid Outpost. :( \$\endgroup\$ May 7 '15 at 19:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.