2016-11-04 70 views
2

我目前正在嘗試改進我的動畫與JavaScript(帆布)的邏輯。帆布網格像系統

我想重現此動畫:http://codepen.io/interaminense/pen/QKxrpE

在開始階段,我不想去列上下。我只想放置所有線並旋轉。

我寫了這個代碼:

構造

function Particle(i, j){ 
    this.y = 15 * i * 2; 
    this.x = 15 * j; 
    particleIndex++; 
    particles[particleIndex] = this; 
    this.id = particleIndex; 
    this.color = "#000000";    
} 

然後,將線:

Particle.prototype.draw = function(){ 
    ctx.fillStyle = this.color; 
    ctx.fillRect(this.x, this.y, 1, 15); 
} 

我試圖把只有一條線:

var test = new Particle(); 
    test.draw(); 

它工作得很好ctly。現在,幾行我認爲做這樣的事情:爲每一行 ,我創建X線:

for(var i=0; i<4; i++){ 
    for(var j=0; j<15; j++){ 
    // First row, i create 15 lines. Second row, I create 15 lines... 
    new Particle(i, j); // i and j for determinate the row and columns 
    } 
} 

然後,我把行:

for(var i in particles){ 
    particles[i].draw(); 
} 

這裏是一個的jsfiddle:https://jsfiddle.net/65pgy0gc/2/

現在,對於旋轉,我認爲最困難的事情是從它自己的中心旋轉對象。我騎着,我必須翻譯,以改變轉換的起源,應用旋轉和翻譯回來。 這樣的事情? :

Particle.prototype.draw = function(){ 
     ctx.fillStyle = this.color; 

     ctx.translate(this.x,this.y); 
     ctx.rotate((Math.PI/180)*angle); 
     ctx.translate(-this.x,-this.y); 

     ctx.fillRect(this.x, this.y, 1, 15); 
    } 
+2

當你調用'新Particle'爲什麼不 「行」,在傳遞和「列」參數,然後用它來設置X和Y的位置? – evolutionxbox

回答

0

試圖扭轉變形是很麻煩的辦法。

要圍繞中心

// x,y center of rect 
// w,h width and height 
// rot in radians 
function draw(x,y,w,h,rot){ 
    ctx.setTransform(1,0,0,1,x,y); // if you want a scale replace the two 1s with scale 
    ctx.rotate(rot); 
    ctx.fillRect(-w/2,-h/2,w,h); 
    // next line is optional 
    ctx.setTransform(1,0,0,1,0,0); // will reset the transform or if you 
            // are calling this function many times in a row 
            // can be done after all the particles have been drawn 

} 
+0

酷!謝謝。有沒有辦法將延遲應用於每個對象?你可以看看我的jsfiddle:https://jsfiddle.net/65pgy0gc/3/。我試圖把一個setTimeout在requestanimationframe中,但它失敗了... – Seabon

+0

@Seabon我看了一下,並將其分支到https://jsfiddle.net/blindman67/ysLf6gzr/1/進行了一些更改。延遲(猜測你想要的)只是每個粒子的計數器,直到粒子可以旋轉爲止。 – Blindman67

+0

正是我想要的!非常聰明; p謝謝 – Seabon