当我尝试递归更改颜色时,我正为错误所困扰。错误为:“未捕获的TypeError无法读取未定义的属性'map'(草图:第18行)”,并引用了这段代码:this.color.levels.map(x => x * 0.9)
。
我认为这是因为递归和“此”上下文存在问题。我创建的“正确”功能仅执行一次,直到抛出上述错误为止。
有什么想法可以做到这一点,或者如何以与我创建的对象相同的方式递归地更改颜色?
我的代码:https://editor.p5js.org/grzegorz.kuguar@gmail.com/sketches/Syc1qQmnQ
<code> class Branch {
constructor(begin, end, strokeW, color, angle) {
this.begin = begin;
this.end = end;
this.angle = angle;
this.strokeW = strokeW;
this.color = color;
}
display() {
stroke(this.color);
strokeWeight(this.strokeW);
line(this.begin.x, this.begin.y, this.end.x, this.end.y);
}
right(angle) {
let direction = p5.Vector.sub(this.end, this.begin);
direction.rotate(angle);
let nextPoint = p5.Vector.add(direction, this.end);
let right = new Branch(this.end, nextPoint, this.strokeW*0.7, this.color.levels.map(x => x * 0.9)); //this line of code throw an error once I am trying to manipulate on the array
return right;
}
}
let tree = [];
let trunk;
let something; //just for check how looks like a p5.color object
function setup() {
createCanvas(400, 400);
background(20);
something = color(100, 230, 100);
console.log(something);
let x = createVector(width/2, height);
let y = createVector(width/2, height-100);
trunk = new Branch(x,y, 7, color(255,100, 100));
tree[0] = trunk;
tree.push(trunk);
}
function draw() {
for(let i = 0; i < tree.length; i++) {
tree[i].display();
}
}
function mousePressed() {
for(let i = tree.length-1; i >= 0; i--) {
tree.push(tree[i].right(Math.PI/4, 0.66));
}
}
答案 0 :(得分:0)
问题在于您使用地图。您正在做
this.col.levels.map(x => x * 0.9)
返回一个数组,而不是p5.Color对象。 要创建新的颜色对象,请使用:
color.apply(this, this.col.levels.map(x => x * 0.9))
您可以看到完整的草图here