Search code examples
javascriptfunctionif-statementdraw

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.

For example: When I click the canvas three times, I can get three ball moving on the 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;
    }
    
};


Solution

  • 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;
        }
    };