2

I have problem with javascript canvas. I'm trying to put on canvas several object which are moving and bouncing on edges of canvas. If i create one object, there is no problem with it, but if i want to create more objects, they become connected.

Fiddle example:

https://jsfiddle.net/mwbgwa39/

I will be very thankfull if someone could help me :)

Dominik
  • 1,233
  • 2
  • 14
  • 29

2 Answers2

2

Important thing is to call beginPath() at the begining of each object drawing and closePath() when you are done drawing that object. If you don't call it canvas thinks that you are trying to continue drawing last object. You can read more on MDN

        for(i in obj_t)
            {
                ctx.beginPath();
                obj_t[i].xPos = obj_t[i].xPos + obj_t[i].xVel;
                obj_t[i].yPos = obj_t[i].yPos + obj_t[i].yVel;
                ctx.arc(obj_t[i].xPos, obj_t[i].yPos, obj_t[i].r, 0, 2 * Math.PI);


                ctx.stroke();
                ctx.fill();
                ctx.closePath(); // optional
            }

EDIT: As Kaiido noticed calling closePath() in this example is not necessary. More info on when you should call closePath() can be found in this SO question.

Community
  • 1
  • 1
csharpfolk
  • 4,124
  • 25
  • 31
2

You're drawing a path. Each time you draw something it continues the path you have made so far. You can move beginPath into the for loop to start a new path for each circle:

        ctx.clearRect(0, 0, 400, 400);
        for(i in obj_t)
        {
            ctx.beginPath();
            // draw here
        }
        ctx.closePath();

See in action: https://jsfiddle.net/mwbgwa39/4/

Gavriel
  • 18,880
  • 12
  • 68
  • 105
  • Thank you! :) Works perfectly :) – Dominik Jan 31 '16 at 12:03
  • closePath is just a lineTo(firstPoint). Useless for a circle shape, it won't "end" the path declaration. – Kaiido Jan 31 '16 at 23:29
  • @Kaiido, correct, I didn't even have it when I tested. The beginPath at the beginning of the look is what does the effect. I just included the closePath, but maybe I'll move it after the look – Gavriel Jan 31 '16 at 23:31