gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:58:45 25 4
gpt4 key购买 nike

我想使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com