如何用Javascript在点击的时候画出一个新的移动球?
How to use Javascript to draw a new moving ball when I click?
我想用鼠标左键单击 canvas 时在随机位置得到一个新的移动球。
例如:
当我点击canvas三次时,我可以让三个球在canvas上移动。
本题来自可汗学院:
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;
}
};
类似于以下内容:
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;
}
};
我想用鼠标左键单击 canvas 时在随机位置得到一个新的移动球。
例如: 当我点击canvas三次时,我可以让三个球在canvas上移动。
本题来自可汗学院:
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;
}
};
类似于以下内容:
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;
}
};