具有递减线宽的简单JS/html5分形树

Simple JS/html5 fractal tree with decrementing line width

本文关键字:JS html5 分形 简单      更新时间:2023-09-26

我想用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();

如果有一种分阶段完成的方法,这样当我点击一个按钮时,它就会添加一个新的分支,那也太好了。不管怎样,我们将非常感谢你的建议。

我创建并调整了一把小提琴,它可以随心所欲。

小提琴

总而言之:每次设置新线宽时,都需要笔划。所以代码看起来是这样的:

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