我编写了一个JavaScript代码,以在单击 Canvas 时多次掉入球中。这是一个实验。
这是代码: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);
    }
}

但是球并没有掉下来。请告诉我我在哪里错了,以便我可以解决它...

最佳答案

您的代码始终在0到3之间循环。但是,一开始,周围没有球。当您尝试到达balls [0],balls [1]和balls [2]时,会出现undefined错误。

您要做的就是将循环更改为:

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

或者,如果您不想更改循环,则可以在开始时初始化3个球:
balls = [ball1, ball2, ball3];

其中ball1,ball2和ball3定义为ball数据类型。

编辑:

据我了解,您有一些上下文,对于每种上下文,您都希望有一个球列表,以便可以绘制它们。

然后:
balls = []

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

并使用其余的相同代码。

09-12 14:19