未释放的动画画布



有人能帮我如何反转动画吗?

var $ = function(id) { return document.getElementById(id); }
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();
var cvs = $('cvs');
var ctx = cvs.getContext('2d');
var x = 0, y = 0, r = 0, count = 0;
x = cvs.width / 2;
y = cvs.height / 2;
time = Math.sqrt( Math.pow(cvs.width, 2) + 
                 Math.pow(cvs.height, 2) ) / 2;
ctx.fillStyle = 'red';
ctx.rect(0, 0, cvs.width, cvs.height);
ctx.fill();
ctx.globalCompositeOperation = "destination-out";
(function animate() {
    if( count >= time ) {
        return false;
    }else {
        ctx.beginPath();
        ctx.arc(x, y, r, 0, Math.PI * 2);
        ctx.fill();
        ctx.closePath();
        r++;
        count++;
        window.requestAnimFrame(animate, 0);
    }
})();

http://jsfiddle.net/j57msxr5/10/

我找不到缩小圆圈的方法。从大到小/点/消失。

我建议采取不同的方法。我会从表示将在画布上绘制的内容的对象开始,并维护这些对象中的状态。然后要停止动画,您可以检查半径是否大于零:

var $ = document.getElementById.bind(document);
var cvs = $('cvs');
var ctx = cvs.getContext('2d');
var circle = {
    x: cvs.height/2,
    y: cvs.width/2,
    radius: cvs.width/2,
    color: 'white',
    animate: function() {
        if (this.radius > 0) {
            this.radius--;
        }
        return this;
    },
    draw: function(ctx) {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI, false);
        ctx.fillStyle = this.color;
        ctx.fill();
        return this;
    }
};
var bg = {
    x: 0,
    y: 0,
    w: cvs.width,
    h: cvs.height,
    color: 'red',
    draw: function(ctx) {
        ctx.fillStyle = this.color;
        ctx.rect(this.x, this.y, this.w, this.h);
        ctx.fill();
    }
};
(function frame() {
    // If you draw your objects in order
    // you don't need to set globalCompositeOperation
    bg.draw(ctx);
    circle.draw(ctx).animate();
    requestAnimationFrame(frame);   
}());

演示:http://jsfiddle.net/9uLrL6d6/

最新更新