随机化一个角度?

时间:2015-07-31 09:03:21

标签: javascript math

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

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

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

enter image description here

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

1 个答案:

答案 0 :(得分:7)

您需要为您的角度添加随机偏移(在±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>

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