我正在尝试绘制一个不规则的圆圈,为草图中的前 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
的看法是正确的。
此外还有另一个错误:
letpoints = [];
可能应该是全局的,否则列表会在每次调用时重置。
尚不清楚 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>
关于javascript - 用点数组绘制不规则圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72230829/