波涛汹涌的移动物体Javascript

时间:2015-06-06 01:22:36

标签: javascript html canvas

好的,所以我通常不会使用javascript,我在这里看到了类似于这个的其他问题,但它们似乎对我不起作用。我正在使用此代码并遇到问题。当我的圆圈/球移动时,它真的起伏不定,好像框架分开或刷新速度慢。我试图让它成为一个非常流畅的移动球。任何帮助在这里将不胜感激。

<script>
    var context;
    var x=100;
    var y=200;
    var dx=5;
    var dy=5;

    function init() {
        context= circleCanvas.getContext('2d');
        setInterval(draw,300);
    }

    function draw() {

        context.clearRect(0,0,300,300);
        context.beginPath();
        context.fillStyle = "rgba(255, 255, 255, 0.5)";
        // Draws a circle of radius 20 at the coordinates 100,100 on the canvas
        context.arc(x,y,40,0,Math.PI*2,true);
        context.closePath();
        context.fill();

        // Boundary Logic
        if( x<0 || x>300) dx=-dx;
        if( y<0 || y>300) dy=-dy;
        x+=dx;
        y+=dy;
    }
</script>

<body onload="init()">
    <%= render "layouts/header"%>
    <%= yield %>
    <canvas id="circleCanvas", width="1000", height="1000">
    </canvas>

</body>

2 个答案:

答案 0 :(得分:2)

帧之间的时间为300ms,而16.7ms(60 fps)或33.4ms(30 fps)。另外,不要使用setInterval / setTimeout来设置动画 - 它们非常不准确,无法使用小数值而无法同步以监控更新。

requestAnimationFrame会给你完美的同步和时间 - 一个小的修改应该会让你到那里。使用小步长值(dx / dy)来调整速度。

function init() {
    context= circleCanvas.getContext('2d');
    requestAnimationFrame(draw);              // start, see below
}

function draw() {

    context.clearRect(0,0,300,300);
    context.beginPath();
    context.fillStyle = "rgba(255, 255, 255, 0.5)";
    // Draws a circle of radius 20 at the coordinates 100,100 on the canvas
    context.arc(x,y,40,0,Math.PI*2,true);
    context.closePath();
    context.fill();

    // Boundary Logic
    if( x<0 || x>300) dx=-dx;
    if( y<0 || y>300) dy=-dy;
    x+=dx;
    y+=dy;

    requestAnimationFrame(draw);    // loop here
}

提示:fillStyle可能很昂贵。如果颜色没有改变,只需在循环外设置一次。 closePath()无需fill()

答案 1 :(得分:0)

将间隔改为更小的间隔;如果增量为5像素,间隔为300毫秒,则移动速度非常慢(每秒仅15像素)。我先尝试了10ms而且发疯了!

function init() {
    context= circleCanvas.getContext('2d');
    setInterval(draw,20);
}
相关问题