p5.js: 用直线而不是椭圆制作动画螺旋?

p5.js: make an animated spiral with line instead of ellipse?

我正在尝试使用一条线来制作螺旋动画,但似乎只能使用椭圆来让它工作。

有谁知道如何用 line() 替换 ellipse()?

代码如下:

var angle = 0.0;
var offset = 60;
var scalar = 10;
var speed = 0.05;

function setup() {
  createCanvas(600, 120);
  fill(0);
}

function draw() {
  var x = offset + cos(angle) * scalar;
  var y = offset + sin(angle) * scalar;
  ellipse( x, y, 2, 2);
  angle += speed;
  scalar += speed;
}

假设您想使用线段立即绘制整个螺旋线,您只需要一个 for 循环来计算螺旋线中当前点和下一个点的 x 和 y 坐标以进行一些变化增量,然后在每对点之间画线。写这样一个 for 循环当然有很多方法,这取决于约束是什么(你想要在你的螺旋中有特定数量的环吗?特定数量的旋转度数?),但重要的是你的变化增量越大你的螺旋看起来不太光滑。下面是一个使用鼠标位置来确定环数和变化增量大小的例子:

function setup() {
  createCanvas(windowWidth, windowHeight);
  stroke(0);
  strokeWeight(4);
  textAlign(LEFT, TOP);
}

function draw() {
  background(255);
  
  // let the horizontal mouse position indicate the
  // size of the steps
  let speed = map(mouseX, 0, width, 0.01, 1, true);

  // let the vertical mouse position indicate the
  // total amount of rotation
  let maxRotation = map(mouseY, 0, height, TWO_PI, TWO_PI * 50, true);
  
  push();
  noStroke();
  fill('red');
  text(`Rings: ${(maxRotation / TWO_PI).toFixed(1)}, Speed: ${speed.toFixed(2)}`, 10, 10);
  pop();
  
  translate(width / 2, height / 2);
  
  let scalar = 10;
  if (speed <= 0) {
    console.error('cannot have <= 0 speed');
    return;
  }
  for (let angle = 0; angle < maxRotation; angle += speed, scalar += speed) {
    const x = cos(angle) * scalar;
    const y = sin(angle) * scalar;
    
    const x2 = cos(angle + speed) * (scalar + speed);
    const y2 = sin(angle + speed) * (scalar + speed);
    line(x, y, x2, y2);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>