【问题标题】:Clearing canvas save animations already running清除画布保存动画已经运行
【发布时间】:2013-09-28 01:21:08
【问题描述】:

我正在尝试学习 2d 画布动画,但不知道如何让已创建的动画保持运行。

例如:单击时,我创建了一个运行到屏幕左上角的圆圈,但是当我再次单击时,该动画被清除并开始新的动画。我希望一次运行不止一个圆圈。

代码:

window.requestAnimFrame=(function(callback){
    return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){
        window.setTimeout(callback,1000/60);
    };
})();

var can = $('canvas')[0],
    ctx = can.getContext('2d'),
    width = window.innerWidth,
    height = window.innerHeight-5,
    color = '';

can.width = width;
can.height = height;
can.addEventListener('click',randomColor);
can.addEventListener('click',animate);

var circle = {
    x:0,
    y:0,
    r:5,
    d:2*Math.PI,
    color:''
}

function drawCircle(){
    ctx.beginPath();
    ctx.arc(circle.x,circle.y,circle.r,0,circle.d,false);
    ctx.fillStyle = circle.color;
    ctx.fill();
}

function randomColor(){
    color = 'rgba('+Math.floor(Math.random()*255)+','+Math.floor(Math.random()*255)+','+Math.floor(Math.random()*255)+',1)';
}

function clear(){
    ctx.clearRect(0,0,can.width,can.height);
}

function animate(event,startTime){
    if(startTime==undefined){
        startTime = (new Date()).getTime();
    }
    circle.x = event.clientX;
    circle.y = event.clientY;
    circle.color = color;
    var time = (new Date()).getTime()-startTime;
    var speed = (300*time/1000);
    circle.x += speed;
    circle.y -= speed;
    if (circle.x+circle.r>width||circle.y<0||circle.y>height||circle.x<0) {
        return;
    }
    clear();
    drawCircle();
    requestAnimFrame(function(){
        animate(event,startTime);
    });
}

【问题讨论】:

    标签: javascript jquery animation canvas


    【解决方案1】:

    我认为画布的清除不是问题。

    我将如何处理它:

    circle 变成一个对象而不是一个变量。

    现在创建一个新函数addCircle(),它创建一个新的圆对象并将其添加到您的画布和圆列表中(您可以在此处使用您的drawCircle() 函数)。

    修改您的 animate() 函数,使其遍历您的新圈子列表,从而移动每个圈子。

    这至少应该让你走上正轨。

    【讨论】:

      猜你喜欢
      • 2012-07-26
      • 1970-01-01
      • 2012-07-19
      • 2017-06-21
      • 2020-08-21
      • 1970-01-01
      • 2017-03-26
      • 2014-11-07
      • 1970-01-01
      相关资源
      最近更新 更多