javascript - 我如何缩短这段将圆圈变成数组的代码?

标签 javascript p5.js

我正在使用 p5.js 库,无法正确格式化 for 循环来显示这些圆圈:

function draw() {
  ellipse(width/12,height/2,width/6,width/6);    
  ellipse(width/12,height/4,width/12,width/12);
  ellipse(width/12,height/8,width/24,width/24);
  ellipse(width/12,height/16,width/48,width/48);
}

我已尝试以下操作,但没有省略号。我哪里出错了?

下面我附上了完整的代码。

for(var i = 0; i < 4; i++){
  ellipse(width/12, height/(2 * (2^i)), width/(6 * (2^i)), width/(6 * (2^i));  
}

function setup() {
  canvas = createCanvas(windowWidth,windowHeight);
}

function draw() {
  background(255);
  fill(	149, 185, 241,160);
  rect(width*(1/6),0,width*(2/3),height);
  
  
  fill(181,99,87,160);
  noStroke();
  
  for(var i = 0; i < 4; i++){
  ellipse(width/12, height/(2* pow(2,i)), width/(6 * pow(2,i)), width/(6 * pow(2,i));  
}

  
}


window.onresize = function() {
  canvas.size(windowWidth, windowHeight);
}

最佳答案

这并没有按照您的想法进行:

2^i

这是一个按位异或运算符。请参阅this question了解更多信息,Google 是您的 friend 。

您可能正在寻找 P5.js pow() 函数。更多信息可参见the reference .

你应该养成debugging的习惯你的代码。当您有这样的问题时,请尝试打印出每个参数的值。您本来就能够隔离您的问题,这使得谷歌搜索变得更容易。

例如,执行以下操作:

for(var i = 0; i < 4; i++){
  console.log('i: ' + i);
  console.log('width: ' + width);
  console.log('width/12: ' + width/12);
  console.log('pow(2,i): ' + pow(2,i));
  console.log('height/(2* pow(2,i)): ' + height/(2* pow(2,i)));
  console.log('width/(6 * pow(2,i)): ' + width/(6 * pow(2,i)));
  ellipse(width/12, height/(2* pow(2,i)), width/(6 * pow(2,i)), width/(6 * pow(2,i)));  
}

这将准确地告诉您哪个参数与您的预期不同,您可以从那里进一步隔离您的问题。

当然,这还需要您检查 developer console ,你也应该真正养成这样做的习惯。那里将显示您遇到的任何错误。您问题中当前的代码在 ellipse() 行上缺少 ) 右括号。​​

如果您有后续问题,请尝试发布 MCVE我们可以复制并粘贴来运行自己,而不是断开连接的代码片段。

关于javascript - 我如何缩短这段将圆圈变成数组的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44851250/

相关文章:

javascript - p5.j​​s 顶点形状换行

node.js - p5.j​​s 和 node.js 为小 Blob 同步 x 和 y 的位置

javascript - Number.prototype.function 不适用于 jQuery(..).val() 的结果

javascript - Sails.js 在 js 文件更改时运行 Assets 管道

node.js - 如何通过 Node.js(和 create-react-app)使用 p5.js 声音库预加载

javascript - 使用 p5.js 从一个场景过渡到下一个场景

javascript - While 循环在 P5.js 函数中不起作用

javascript - 默认情况下启用 Crankshaft 的是哪个版本的 NodeJS?

javascript - 无法在angularjs中进行双向数据绑定(bind)

javascript - 为什么 props 在 render 和 componentWillReceiveProps 中显示不同的值?