Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【译】无序方块—Cubic Disarray #23

Open
JChehe opened this issue Aug 11, 2018 · 0 comments
Open

【译】无序方块—Cubic Disarray #23

JChehe opened this issue Aug 11, 2018 · 0 comments

Comments

@JChehe
Copy link
Owner

JChehe commented Aug 11, 2018

原文:Cubic Disarray

Georg Ness 的奇妙作品是生成艺术的真正灵感来源。在本教程中,我们将实现他的作品之一:无序方块。

<canvas> 是页面中唯一的元素,其大小为 300x300 像素。

老规矩,下面是初始步骤,里面没有任何渲染操作。

var canvas = document.querySelector('canvas');
var context = canvas.getContext('2d');
context.lineWidth = 2;

var size = window.innerWidth;

canvas.width = size;
canvas.height = size;

var squareSize = 30;

squareSize 变量用于指定方块的尺寸大小。

现在,创建一个用于绘制方块的函数。该函数十分简单,仅接受 width 和 height 参数。方块位置由另一个循环处理。

function draw(width, height) {
  context.beginPath();
  context.rect(-width/2, -height/2, width, height);
  context.stroke(); 
}

通过循环将屏幕填满方块。这里我们使用上下文 contextsavetranslaterestore 方法移动上下文坐标系,然后调用上面定义的 draw 方法进行绘制。

for( var i = squareSize; i <= size - squareSize; i += squareSize) {
  for( var j = squareSize; j <= size - squareSize; j+= squareSize ) {
    context.save();
    context.translate(i, j);
    draw(squareSize, squareSize);
    context.restore();
  }
}

齐整的方块们

现在屏幕铺整整齐齐地铺满了方块,为“无序”打下了基础。

引入随机是十分简单的:首先定义变量,一个用于指定方块的相对位移距离,另一个是旋转角度。

var randomDisplacement = 15;
var rotateMultiplier = 20;

这样我们就可以利用这些变量创建随机的位移和旋转值,并且越靠近 canvas 底部值越大。

var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
var rotateAmt = j / size * Math.PI / 180 * plusOrMinus * Math.random() * rotateMultiplier;

plusOrMinus = Math.random() < 0.5 ? -1 : 1;
var translateAmt = j / size * plusOrMinus * Math.random() * randomDisplacement;

然后应用位移和旋转值。

context.translate( i + translateAmt, j)
context.rotate(rotateAmt);

最终效果——无序方块

这就是我们拥有的:无序方块!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant