2016-12-18 2 views
0

Here - анимация круга, скользящего взад и вперед по горизонтали. Потребуется 10 секунд, чтобы круг прошел от -100 до 300 назад до -100.HTML Canvas: Delay Animation

Это моя drawCircle() функция, которая вызывается через requestAnimationFrame (есть еще код на Codepen):

function drawCircle() { 
    // clean off canvas 
    ctx.clearRect(0, 0, cvs.width, cvs.height); 

    // color in the background 
    ctx.fillStyle = "#EEEEEE"; 
    ctx.fillRect(0, 0, cvs.width, cvs.height); 

    // draw the circle 
    ctx.beginPath(); 
    if (moveRight) { 
    easingValue = easeInOutExpo(iteration, -100, 400, totalIterations); 
    } else { 
    easingValue = easeInOutExpo(iteration, 400, -450, totalIterations); 
    } 
    var radius = 50; 
    ctx.arc(easingValue, 125, radius, 0, Math.PI * 2, false); 
    ctx.closePath(); 

    // color in the circle 
    ctx.fillStyle = "#006699"; 
    ctx.fill(); 

    if (iteration < totalIterations) { 
     iteration++; 
    } else { 
     iteration = 0; 
     moveRight = !moveRight; 
    } 
    requestAnimationFrame(drawCircle); 

} 

Я пытаюсь выяснить, как отложить выполнение другого «анимации.» Поскольку requestAnimationFrame обеспечивает fps 60, эта 5-секундная анимация (10 секунд, включая переход в альтернативном направлении) будет содержать в общей сложности 300 отдельных кадров, или totalIterations. По сути, моя цель состоит в том, чтобы сказать: «Если текущий кадр (iteration) равен totalIterations, вместо того, чтобы немедленно начать, подождите 3 или 5 секунд».

Сущностью, что я думал, что могло бы работать (просто идея):

var intermission = 3; // seconds to defer subsequent animation 
if(elapsedSeconds % intermission === 0) { // every 3 seconds 
    ctx.arc(easingValue, 125, radius, 0, Math.PI * 2, false); // change `x` value with ease 
} else { 
    ctx.arc(-100, 125, radius, 0, Math.PI * 2, false); // stand still off canvas 
} 

Я не имею ни малейшего понятия. Раньше я использовал Canvas.

ответ

1

Почему бы не использовать javascript's setTimeout Функция в рамке, которую вы хотите остановить?

... 
    if (iteration < totalIterations) { 
     iteration++; 
    } else { 
     iteration = 0; 
     moveRight = !moveRight; 
    } 

    if (iteration == 0 && moveRight){ 
    setTimeout(function(){ 
     requestAnimationFrame(drawCircle); 
    }, 3000); 
    }else{ 
    requestAnimationFrame(drawCircle); 
    } 
... 

codpen example

другой вариант в случае, если вы боитесь неточностью функции setTimeout:

if (iteration < totalIterations) { 
     iteration++; 
    } else { 
     iteration = 0; 
     moveRight = !moveRight; 
    } 

    if (iteration == 0 && moveRight){ 
    var next_iter = new Date().getTime() + 3000; 
    delay_restart(next_iter); 
    }else{ 
    requestAnimationFrame(drawCircle); 
    } 

} 
drawCircle(); 

function delay_restart(start) { 
    while (new Date().getTime() < start){ 

    } 
    requestAnimationFrame(drawCircle) 
} 

codepen for second example