Javascript 在HTML5中,如何在直线上添加球,并在每次单击时移动球?
我试图创造这个球移动。因此,每次单击都应该将一个球从右侧添加到线的末端,当动画仍在运行时,球将向左移动,直到消失。因此,如果我点击按钮5次,我应该有5个球在同一时间移动,但第一个会先移动,然后是其余的球。距离应取决于单击按钮的时间 这是我到目前为止得到的Javascript 在HTML5中,如何在直线上添加球,并在每次单击时移动球?,javascript,jquery,html,html5-canvas,Javascript,Jquery,Html,Html5 Canvas,我试图创造这个球移动。因此,每次单击都应该将一个球从右侧添加到线的末端,当动画仍在运行时,球将向左移动,直到消失。因此,如果我点击按钮5次,我应该有5个球在同一时间移动,但第一个会先移动,然后是其余的球。距离应取决于单击按钮的时间 这是我到目前为止得到的 // RequestAnimFrame: a browser API for getting smooth animations window.requestAnimFrame = (function() { return window
// RequestAnimFrame: a browser API for getting smooth animations
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ) {
return window.setTimeout(callback, 1000 / 60);
};
})();
var loop = 400;
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
function drawALine() {
context.beginPath();
context.moveTo(10, 10);
context.lineTo(400, 10);
context.stroke();
}
function drawABall(positionX) {
context.beginPath();
context.arc(positionX, 10, 5, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
}
function clearScreen() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
function animloop() {
loop = loop - 1;
init = requestAnimFrame(animloop);
clearScreen();
drawALine();
drawABall(loop);
}
jQuery('#addBall').click(function() {
animloop();
drawABall(0);
});
你可以列一张球的清单
var balls = [];
每次单击,您都可以向列表中添加一个新的Ball
对象:
jQuery('#addBall').click(function() {
balls.push(new Ball());
});
Ball
对象如下所示:
function Ball() {
this.pos = 400;
this.render = function() {
this.pos -= 1;
context.beginPath();
context.arc(this.pos, 10, 5, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
};
}
function animloop() {
requestAnimFrame(animloop);
clearScreen();
drawALine();
for(var i = 0; i < balls.length; i++) {
balls[i].render();
}
}
现在,您的animLoop
函数如下所示:
function Ball() {
this.pos = 400;
this.render = function() {
this.pos -= 1;
context.beginPath();
context.arc(this.pos, 10, 5, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
};
}
function animloop() {
requestAnimFrame(animloop);
clearScreen();
drawALine();
for(var i = 0; i < balls.length; i++) {
balls[i].render();
}
}
函数animloop(){
请求动画帧(animloop);
清除屏幕();
drawALine();
对于(变量i=0;i
我已经为此做了一个