Javascript error when dropping balls

I wrote javascript code to throw the ball multiple times when clicking on the canvas. This is an experiment. Here is the code:
HTML

<br style="clear: both" />
<canvas id="myCanvas1" width="134px" height="331px" onclick="draw(0)"></canvas>
<canvas id="myCanvas2" width="134px" height="331px" onclick="draw(1)"></canvas>
<canvas id="myCanvas3" width="134px" height="331px" onclick="draw(2)"></canvas>

      

JAVASCRIPT

    var balls = [[], [], []],
    canvases = document.getElementsByTagName('canvas'),
    context = [],
    interval,
    boxWidth = 150,
    ballRadius = 10,
    canvasHeight = 235;
for (var i = 0; i < canvases.length; i++) {
    context.push(canvases[i].getContext('2d'));
}

function draw() {
    var movement = false;
    for (var i = 0; i < 3; i++) {
        context[i].clearRect(0, 0, boxWidth, canvasHeight);
        for (var j = 0; j < balls[i].length; j++) {
            if (balls[i][j].y < balls[i][j].yStop) {
                balls[i][j].y += 4;
                movement = true;
            }
            context[i].beginPath();
            context[i].fillStyle = "red";
            context[i].arc(balls[i][j].x, balls[i][j].y, ballRadius, 0, Math.PI * 2, true);
            context[i].closePath();
            context[i].fill();
        }
    }
    if (!movement) {
        clearInterval(interval);
        interval = null;
    }
}

function newBall(n) {
    console.log('new ball', n);
    var last = balls[n][balls[n].length - 1],
        ball = {x: ballRadius, y: ballRadius, yStop: canvasHeight - ballRadius};
    if (last) {
        if (last.x < boxWidth - ballRadius * 3) {
             ball.x = last.x + ballRadius * 2;
             ball.yStop = last.yStop;
        } else {
             ball.yStop = last.yStop - ballRadius * 2;
        }
    }
    balls[n].push(ball);
    if (!interval) {
        interval = setInterval(draw, 10);
    }
}

      

But the balls don't go in. Please tell me where am I going wrong to fix this ...

+3


source to share


2 answers


Your code always loops from 0 to 3. However, there is no ball at first. When you try to get to balls [0], balls [1] and balls [2], you get an error undefined

.

What you need to do is change the loop to:

for (var i = 0; i < balls.length; i++)

      

or if you don't want to change the loop, you can initialize 3 balls at the beginning:

balls = [ball1, ball2, ball3];

      

where ball1, ball2 and ball3 are defined as the type of your ball.



EDIT:

As I understand it, you have multiple contexts, and for each context, you want to have a list of balls so you can draw them.

Then:

balls = []

for (var i = 0; i < canvases.length; i++) {
    context.push(canvases[i].getContext('2d'));
    balls.push([]);
}

      

and use the rest of the code.

+1


source


balls

[]

when starting the cycle. So balls[0]

there is undefined and therefore has no property length

.



+3


source







All Articles