javascript - 简单的 JS/html5 分形树,线宽递减

标签 javascript html tree fractals

我想使用 JS 制作一个非常简单的分形树(用于学习目的)。我一直在使用从维基百科文章中获得的以下代码。太棒了,只是我希望线宽随着每次迭代而减小。正如你所看到的,我尝试了 context.lineWidth = context.lineWidth - 1,但这不起作用。有人对如何实现这一目标有任何想法吗?

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

context.fillStyle = '#000';
context.lineWidth = 20;

var deg_to_rad = Math.PI / 180.0;
var depth = 9;

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

}
context.beginPath();
drawTree(300, 500, -90, depth);
context.closePath();
context.stroke();

如果有一种方法可以分阶段执行此操作,这样当我单击按钮时它会添加一个新分支,那就太好了。无论如何,我们将非常感谢您的建议。

最佳答案

我创建并调整了一个 fiddle ,它以某种方式实现你想要的。

fiddle

总而言之:每次设置新的线宽时都需要描边。所以代码如下所示:

function drawLine(x1, y1, x2, y2, lw){
    context.beginPath();
    context.moveTo(x1, y1);
    context.lineTo(x2, y2);
    context.lineWidth = lw;
    context.closePath();
    context.stroke();
}

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

drawTree(300, 500, -90, depth, depth);

关于javascript - 简单的 JS/html5 分形树,线宽递减,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25947326/

相关文章:

javascript - JS 对象和函数更正

html - 使用不同的字体大小垂直对齐 Bootstrap 中的标题

html - 移动 HTML Canvas 元素的 "camera"

c++ - 此代码有什么问题?它永无止境(二叉树的顶 View )

javascript - 如何保护 public_html 中的文件夹免受访问者的侵害

javascript - Normalizr - 如何生成与父实体相关的 slug/id

hibernate - 用于获取单个树中所有节点的 JPA 查询

c++ - 使用最小生成树查找从 A 到 B 的路径 - C/C++

javascript - 从父到子 iFrame 使用 postMessage 发出通信

javascript - while 循环中从日期到日期的计数