简体   繁体   English

如何使用Javascript点击时绘制一个新的移动球?

[英]How to use Javascript to draw a new moving ball when I click?

I wanna get a new moving ball in random position when I click the canvas with mouse left button.当我用鼠标左键单击 canvas 时,我想在随机 position 中获得一个新的移动球。

For example: When I click the canvas three times, I can get three ball moving on the canvas.例如:当我点击 canvas 三次时,我可以得到三个球在 canvas 上移动。

This question is from the Khan academy:这个问题来自可汗学院:

My Code 我的代码

 var positionX = 20; var positionY = 20; var speed; var controlSpeed=5; var randomNum=random(0,400); var randomNum2=random(0,400); //repeat draw = function() { background(202, 255, 97); fill(66, 66, 66); positionX = positionX + speed; positionY = positionY + speed; //ellipse repeatDraw ellipse(positionX, 200, 50, 50); ellipse(200, positionY, 50, 50); // if (positionX > 375) { speed = -controlSpeed; } if (positionX < 25) { speed = controlSpeed; } if (positionY > 375) { speed = -controlSpeed; } if (positionY < 25) { speed = controlSpeed; } };

Something like the following:类似于以下内容:

var balls = [];

//repeat
draw = function() {
    if (mouseIsPressed) {
        balls.push({x: random(0, 400), y: random(0, 400), vx: random(-10, 10), vy: random(-10, 10), r: 50});
    }
    
    background(202, 255, 97);
    fill(66, 66, 66);
    
    for (var i = 0; i < balls.length; i++) {
        var ball = balls[i];
        ellipse(ball.x, ball.y, ball.r, ball.r);
        ball.x += ball.vx;
        ball.y += ball.vy;
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM