如何在HTML5中移动一条线?

时间:2014-03-29 21:10:15

标签: javascript html5 animation

我正在尝试单击一个简单的画布应用程序来演示我的演示文稿。只需单击按钮,就会有一个球以恒定的速度从左向右移动。我只是想展示一系列事件。

这是我开始的地方并不多。 http://jsfiddle.net/noppanit/z5VwL/1/

<canvas id="myCanvas" width="578" height="200"></canvas>

<input type="button" onclick="clickToAddBall()" value="Click"/>



    var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

context.beginPath();
context.moveTo(10, 10);
context.lineTo(400, 10);
context.stroke();


function clickToAddBall() {
    // Do something
}

function gameLoop() {
    var loop = 400;
    setInterval(function() {
        loop = loop - 10;
        drawABall(loop);
    }, 200);
}
gameLoop();

function drawABall(positionX) {
      var centerX = canvas.width / 2;
      var centerY = canvas.height / 2;
      var radius = 5;

      context.beginPath();
      context.arc(positionX, 10, radius, 0, 2 * Math.PI, false);
      context.fillStyle = 'green';
      context.fill();
      context.lineWidth = 5;
      context.strokeStyle = '#003300';
      context.stroke();
}

1 个答案:

答案 0 :(得分:2)

begginers的简单画布结构:

1)动画循环:

    // 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 / 1000);
        };
})();
window.cancelRequestAnimFrame = (function() {
    return window.cancelAnimationFrame              ||
        window.webkitCancelRequestAnimationFrame    ||
        window.mozCancelRequestAnimationFrame       ||
        window.oCancelRequestAnimationFrame         ||
        window.msCancelRequestAnimationFrame        ||
        clearTimeout
} )();

2)创建球

    ball = {
    x: canvas.width / 2 - 10,
    y: canvas.height / 2 ,
    r: 12,
    c: 'white',
    vx: 8,
    vy: 8,

    // function for drawing ball on canvas
    draw: function() {
        ctx.beginPath();
        ctx.fillStyle = this.c;
        ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false);
        ctx.fill();
    }

3)例如,将EventListener添加到窗口,在处理程序中我们运行动画:

var canvas = document.getElementById('mycanvas'),
var run = true;
canvas.addEventListener("mousedown", btnClick, true);
function btnClick(e) {
    if(run){
                    ball.draw();
        animloop();
        run = false;
    }
}

4)使用更新功能,在每一帧上改变球的x,y位置。

function Update() {
    // Move the ball
    ball.x += ball.vx;
    ball.y += ball.vy;
}

5)绘制所有内容的函数,unlimeted循环:

function animloop() {
    init = requestAnimFrame(animloop);
    Update();
}

6)球将从画布窗口消失。对于它你需要碰撞检测。如果ball.x&gt; some.value THEN ball.vx = 0;如果您不需要vy,可以将其设置为零。祝你好运!