簡體   English   中英

我該如何縮短將圓圈變成數組的代碼?

[英]how do i make shorten this code that makes circles into an array?

我正在使用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

那是按位異或運算符。 有關更多信息,請參見此問題 ,Google是您的朋友。

您可能正在尋找P5.js pow()函數。 參考資料中可以找到更多信息。

您應該養成調試代碼的習慣。 遇到類似問題時,請嘗試打印每個參數的值。 您本來可以找出問題的所在,因此可以更輕松地進行Google搜索。

例如,執行以下操作:

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)));  
}

這將准確告訴您哪個參數與您期望的不同,並且您可以從那里進一步隔離問題。

當然,這還需要您檢查開發人員控制台 ,您也應該真正養成這樣做的習慣。 那就是顯示您遇到的任何錯誤的地方。 您問題中的當前代碼缺少)ellipse()行上的ellipse()括號。

如果您有后續問題,請嘗試發布一個MCVE ,我們可以復制並粘貼該MCVE以便自己運行,而不是斷開連接的代碼段。

您可以使用左移<<運算符,因為您使用的是因子2,例如

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

 console.log(2 << 0, 2 << 1, 2 << 2, 2 << 3); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM