当前位置: 代码迷 >> JavaScript >> 随机化一个角度?
  详细解决方案

随机化一个角度?

热度:93   发布时间:2023-06-05 11:58:03.0

 var elem = document.getElementById('canvas'); var context = elem.getContext('2d'); context.fillStyle = '#000'; context.lineWidth = 1; var depth = 9; function drawLine(x1, y1, x2, y2, brightness){ context.moveTo(x1, y1); context.lineTo(x2, y2); } function drawTree(x1, y1, angle, depth){ if (depth !== 0){ var thisAngle = angle*(Math.random()-0.5) var x2 = x1 + (Math.cos(thisAngle) * depth * 10.0); var y2 = y1 + (Math.sin(thisAngle) * depth * 10.0); drawLine(x1, y1, x2, y2, depth); drawTree(x2, y2, angle - 0.34906585, depth - 1); drawTree(x2, y2, angle + 0.34906585, depth - 1); } } context.beginPath(); drawTree(300, 500, -1.57, depth); context.closePath(); context.stroke(); 
 <html> <body> <canvas id="canvas" width="1000" height="700"></canvas> </body> </html> 

我有一个在画布中绘制树形的函数:

function drawTree(x1, y1, angle, depth){
  if (depth !== 0){
    var x2 = x1 + (Math.cos(angle) * depth * 10.0);
    var y2 = y1 + (Math.sin(angle) * depth * 10.0);
    drawLine(x1, y1, x2, y2, depth);
    drawTree(x2, y2, angle - 0.34906585, depth - 1);
    drawTree(x2, y2, angle + 0.34906585, depth - 1);
  }
}

我试图将分形随机化一点,使它看起来更有机。 我试过这个:

function drawTree(x1, y1, angle, depth){
  if (depth !== 0){
    var thisAngle = angle*(Math.random()-0.5)
    var x2 = x1 + (Math.cos(thisAngle) * depth * 10.0);
    var y2 = y1 + (Math.sin(thisAngle) * depth * 10.0);
    drawLine(x1, y1, x2, y2, depth);
    drawTree(x2, y2, angle - 0.34906585, depth - 1);
    drawTree(x2, y2, angle + 0.34906585, depth - 1);
  }
}

出于某种原因,这似乎是偏向于价值0。树向右倾斜。 我不明白为什么。

您需要在角度上添加一个随机偏移(在±0.5或更小的范围内),而不是乘以该因子。

 var elem = document.getElementById('canvas'); var context = elem.getContext('2d'); context.fillStyle = '#000'; context.lineWidth = 1; var depth = 9; function drawLine(x1, y1, x2, y2, brightness){ context.moveTo(x1, y1); context.lineTo(x2, y2); } function drawTree(x1, y1, angle, depth){ if (depth !== 0) { var delta = Math.random()-0.5; var x2 = x1 + (Math.cos(angle + delta) * depth * 10.0); var y2 = y1 + (Math.sin(angle + delta) * depth * 10.0); drawLine(x1, y1, x2, y2, depth); drawTree(x2, y2, angle - 0.34906585, depth - 1); drawTree(x2, y2, angle + 0.34906585, depth - 1); } } context.beginPath(); drawTree(300, 500, -1.57, depth); context.closePath(); context.stroke(); 
 <html> <body> <canvas id="canvas" width="1000" height="700"></canvas> </body> </html> 

您可能还希望尝试更改传递给递归调用的角度(例如,使用修改后的角度而不是原始角度)。

  相关解决方案