Javascript 帆布网格系统
我目前正试图通过使用Javascript(画布)制作动画来改进我的逻辑 我想复制这个动画: 首先,我不想让专栏上下波动。我只想放置所有的线并使它们旋转 我写了这段代码: 构造器Javascript 帆布网格系统,javascript,canvas,grid,Javascript,Canvas,Grid,我目前正试图通过使用Javascript(画布)制作动画来改进我的逻辑 我想复制这个动画: 首先,我不想让专栏上下波动。我只想放置所有的线并使它们旋转 我写了这段代码: 构造器 function Particle(i, j){ this.y = 15 * i * 2; this.x = 15 * j; particleIndex++; particles[particleIndex] = this; this.id = particleIndex; this
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();
它工作得很好。现在,对于几行,我想这样做:
对于每一行,我创建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
}
}
下面是一个JSFIDLE:
现在,对于旋转,我认为最困难的事情是从物体自身的中心旋转物体。为了改变变换原点,应用旋转和向后平移,我必须进行平移。
像这样的
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);
}
尝试反转转换会带来很多麻烦 围绕中心旋转
// 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
}
- 更多关于旋转的信息
- 还有一些通用的
// 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
}