Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript error while dropping balls

I wrote a javascript code to drop in ball multiple times when clicked on canvas. It 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 balls aren't dropping in. Please tell me that where am I wrong so that I can fix it...

like image 244
qwertymaster Avatar asked Apr 28 '26 09:04

qwertymaster


1 Answers

balls is [] when the loop starts. So balls[0] is undefined, and thus has no property length.

like image 127
nathancahill Avatar answered Apr 30 '26 23:04

nathancahill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!