如何在线上添加球并在HTML5中每次单击移动球?

时间:2014-03-30 20:31:47

标签: javascript jquery html5 html5-canvas

我正试图让这个球移动。因此,每次点击它都应该从右侧向球的末端添加一个球,并且当动画仍然运行时,球将向左移动直到它消失。因此,如果我单击按钮5次,我应该同时移动5个球,但第一个将首先跟随其余的球。距离应取决于点击按钮的时间。

这是我到目前为止所得到的。

// 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);
});

http://jsfiddle.net/noppanit/z5VwL/6/

1 个答案:

答案 0 :(得分:1)

你可以制作一个球列表

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();
    };
}

所以现在你的animLoop函数看起来像这样:

function animloop() {
    requestAnimFrame(animloop);

    clearScreen();
    drawALine();
    for(var i = 0; i < balls.length; i++) {
        balls[i].render();
    }
}

我为此做了 jsFiddle

相关问题