如何从数组中获取最新添加的Spot对象的颜色值?
解决获取数组中最新Spot对象颜色的问题
我太懂你折腾好几个小时脑子一团乱的感觉了!别慌,你的目标#4其实只需要简单调整lastColor函数的逻辑就能搞定,咱们一步步来:
问题根源
你当前的lastColor函数只是返回了固定的白色color(255),并没有真正去访问spots数组里最新添加的Spot对象的颜色属性。
修正方案
数组的最后一个元素(也就是最新添加的Spot)可以通过spots[spots.length - 1]获取(因为数组索引从0开始,长度减一就是最后一项的位置),然后直接访问它的color属性即可。另外为了避免数组为空时报错,我们可以加个兜底判断:
function lastColor() { // 如果还没添加任何Spot,返回默认白色;否则返回最新Spot的颜色 if (spots.length === 0) { return color(255); } // #4 成功返回最新添加的Spot的颜色 return spots[spots.length - 1].color; }
完整修正后的代码
把上面的函数替换到你的代码里,完整代码如下:
function mousePressed() { saveSpot(); print(spots); } function saveSpot() { let newSpot = new Spot(mouseX, mouseY, currentColor()); spots.push(newSpot); } function lastColor() { if (spots.length === 0) { return color(255); } // #4 返回数组中最新添加的Spot的颜色值 return spots[spots.length - 1].color; } function drawLastColor() { fill(lastColor()); textSize(50); text("L", 10, 50); } function currentColor() { return color(0, mouseX, mouseY); } class Spot { constructor(x, y, color) { this.x = x; this.y = y; this.color = color; this.size = 25; } draw() { noStroke(); fill(this.color); ellipse(this.x, this.y, this.size, this.size); } }
这样当你点击鼠标添加Spot后,drawLastColor函数就能正确用最新Spot的颜色绘制文本"L"了。
内容的提问来源于stack exchange,提问作者D.Quinlan
相关产品推荐
相关产品推荐

