Chaos Game 分形渲染不正确

Chaos Game fractal not rendering correctly

我正在尝试编写将根据 Chaos game

生成分形的代码

特别是,我正在尝试调试此分形的错误 generation/rendering:

我在 Canvas 元素中使用 Javascript 执行此操作。相关Javascript如下:

canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');

//constants
border = 10  //cardinal distance between vertices and nearest edge(s)

class Point{
  constructor(_x, _y){
    this.x = _x;
    this.y = _y;
  }
}

vertices = []
secondLastVertex = 0;
lastVertex = 0;

//vertices in clockwise order (for ease of checking adjacency)
vertices.push(new Point(canvas.width / 2, border));  //top
vertices.push(new Point(canvas.width - border, canvas.height * Math.tan(36 * Math.PI / 180) / 2));  //upper right
vertices.push(new Point(canvas.width * Math.cos(36 * Math.PI / 180), canvas.height - border));  //lower right
vertices.push(new Point(canvas.width * (1 - (Math.cos(36 * Math.PI / 180))), canvas.height - border));  //lower left
vertices.push(new Point(border, canvas.height * Math.tan(36 * Math.PI / 180) / 2));  //upper left

//move half distance towards random vertex but it can't neighbor the last one IF the last two were the same
function updatePoint(){
  //pick a random vertex
  v = Math.floor(Math.random() * vertices.length);

  if(lastVertex == secondLastVertex)
    //while randomly selected vertex is adjacent to the last approached vertex
    while((v == (lastVertex - 1) % 5) || (v == (lastVertex + 1) % 5))
      //pick another random vertex
      v = Math.floor(Math.random() * vertices.length);

  //cycle the last two vertices
  secondLastVertex = lastVertex;
  lastVertex = v;

  //move half way towards the chosen vertex
  point.x = (vertices[v].x + point.x) / 2;
  point.y = (vertices[v].y + point.y) / 2;
}

//starting point (doesn't matter where)
point = new Point(canvas.width / 2, canvas.height / 2);

for (var i = 0; i < 1000000; i++){
  //get point's next location
  updatePoint();
  
  //draw the point
  context.fillRect(Math.round(point.x), Math.round(point.y), 1, 1);
}

生成的效果图如下所示:

到目前为止,我无法确定是什么导致渲染如此倾斜和错误。一种可能性是我误解了生成此分形的规则(即“如果最后两个顶点相同,则从当前位置向不与最后一个顶点相邻的随机顶点移动一半距离”)

另一个是我在绘制分形时遇到了一些错误。但是,经过 rule/starting-vertex 修改的相同代码能够完美地绘制 Sierpinkski triangle/carpet 甚至其他五边形分形之类的东西。尽管另一个五边形分形最终出现了一些奇怪的倾斜和“每个自相似子结构的右下四分之一”的怪异。

我试着对我解释规则的方式做了一些细微的修改(例如,“如果最后两个顶点相同,下一个顶点不能与前一个顶点相邻或等于”),但没有类似的帮助。我也尝试在绘制之前不舍入目标点的坐标,但是虽然这稍微改变了细节的 character/sharpness,但它并没有改变绘图的任何更大规模的特征。

正如 ggorlen 所指出的,我的问题是我没有正确比较顶点的邻接性。我错误地认为 Javascript 将类似 (-1 % 5) 的值计算为 4,而不是 -1。

为了解决这个问题,我将 4 添加到索引而不是减去 1,然后根据 5(顶点数)对其进行修改

这完全修复了渲染。 (不仅在这种情况下,在其他情况下我一直在用不同的分形进行测试)