用一组点绘制一个不规则的圆

Drawing an irregular circle with an array of points

我正在尝试绘制一个不规则的圆圈,它为草图中的前 n 个帧设置动画。我想要的是生成点,然后从当前点到前一个点画一条线,但是出现错误。

function irregularCircle(limit) {
  let points = []
  let t = frameCount / 20
  let i = floor(t)
  if (frameCount < limit) {
    let radius = w(.25)
    let x = width/2 + radius*cos(t)*noise(t/2)
    let y = height/2 + radius*sin(t)*noise(t/2)
    let point = createVector(x,y)
    points.push(point)
    let pt = points[i]
    let old_pt = points[i-1]
    stroke(24,34,64,75)
    strokeWeight(w(.001))
    if (frameCount > 1 && frameCount < limit) {
      line(pt.x,pt.y,old_pt.x,old_pt.y)
    }
  }
}

我收到“未捕获的类型错误:无法读取未定义的属性(读取 'x')”的响应。我做错了什么?

编辑:不再出现错误,但仍然没有画圆。

提前致谢。

@danh si 关于 i-1

另外还有一个错误: let points = []; 应该是全局的,否则每次调用都会重置列表。

不清楚 w() 函数的作用,但您应该仔细检查返回的值是否有效。

这是应用了上述注释的代码的调整版本:

let points = [];
  
function setup() {
  createCanvas(300, 300);
}

function draw() {
  irregularCircle(3200);
}

function irregularCircle(limit) {
  let t = frameCount / 20
  let i = floor(t)
  if (frameCount < limit) {
    let radius = 250;
    let x = width/2 + radius*cos(t)*noise(t/2)
    let y = height/2 + radius*sin(t)*noise(t/2)
    let point = createVector(x,y)
    points.push(point)
    let pt = points[i]
    let old_pt = points[i > 0 ? i-1 : 0]
    stroke(24,34,64,75)
    strokeWeight(0.1);
    if (frameCount > 1 && frameCount < limit) {
      line(pt.x,pt.y,old_pt.x,old_pt.y)
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>

由于您将前一个点连接到当前点,您可能不需要继续将点附加到列表:您可以简单地保存对前一个点的引用:

let oldPt;
  
function setup() {
  createCanvas(300, 300);
}

function draw() {
  irregularCircle(3200);
}

function irregularCircle(limit) {
  let t = frameCount / 20
  let i = floor(t)
  if (frameCount < limit) {
    let radius = 250;
    let x = width/2 + radius*cos(t)*noise(t/2)
    let y = height/2 + radius*sin(t)*noise(t/2)
    let pt = createVector(x,y)
    // check if the previous point exists before drawing a line
    if(oldPt){
      if (frameCount > 1 && frameCount < limit) {
        line(pt.x,pt.y,oldPt.x,oldPt.y)
      }
    }
    // now that we've drawn the line we can point the old point to the current point
    oldPt = pt;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>