2014-09-24 85 views
0

任何人都可以幫助我如何做相反的動畫呢?Unreveal動畫畫布

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/

我不能找到一種方法,使圓收縮。從大到小/點/走了。

+0

撥弄半徑。以'r = cvs.width/2'開頭,然後嘗試'r - '而不是'r ++'。 – elclanrs 2014-09-25 00:06:00

+0

已經比那。沒有發生。 – meetmahpuppy 2014-09-25 00:08:35

+0

如果您向後退 – elclanrs 2014-09-25 00:09:16

回答

0

我建議採取不同的方法。我將從代表將在畫布上繪製什麼的對象開始,並在這些對象內維護狀態。然後停止,你可以檢查半徑爲動畫大於零:

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); 
}()); 

DEMO:http://jsfiddle.net/9uLrL6d6/