2016-11-04 91 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