"超过了最大调用堆栈大小“;在处理JS时实现Fractal工厂时出错

"Maximum call stack size exceeded" error while implementing Fractal plant in processing JS

本文关键字:处理 JS Fractal 出错 工厂 实现 过了 quot 调用 堆栈      更新时间:2023-09-26

我正在尝试在处理javascript时实现一个分形工厂(直到级别-6)。即使满足基本条件,我也会得到"超过最大调用堆栈大小"错误。

这是代码:第一个功能自定义绘制线根据长度、角度和原点绘制线。增量功能将角度增加25度。递减功能将角度减小25度。

var customDrawLine = function(x, y, length, angle)
{
    var f={x2:'', y2:''};
    f.x2 = x+(sqrt(sq(length)/(1+sq(tan (angle)))));
    f.y2 = y + ((f.x2-x) * tan (angle));
    line(x, y, f.x2, f.y2);
    return f;
};
var incrementAngle = function(angle)
{
    return (angle+25);
};
var decrementAngle = function(angle)
{
    return (angle-25);
};
var fProductionRule = function(x, y, z, degrees, flag)
{
    var l = {x1:'', y1:''};
    if(flag === 1)
    {
        for (var a=0; a<2;a++)
        {
           l = customDrawLine(l.x1, l.y1, z, degrees);
        }
    }
    else
    {
        l = customDrawLine(l.x1, l.y1, z, degrees);
    }
    return l;
};
var xProductionRule = function(x, y, degrees, nLevel, flag)
{
    var k = {x1:'', y1:''};
    var m;
    k.x1 = x;
    k.y1 = y;
    m = degrees;
    for(var z=0; z<7; z++)
    {
        var f = fProductionRule(k.x1, k.y1, (10-z), m, flag);
        m = incrementAngle(m);
        flag = 1;
        {
            {
                xProductionRule(f.x2,f.y2, m, z);
            }
            m = decrementAngle(m);
            xProductionRule(f.x2,f.y2, m, z);
        }
        m = decrementAngle(m);
        f = fProductionRule(k.x1, k.y1, (10-z), m, flag);
        {
            m = decrementAngle(m);
            f = fProductionRule(k.x1, k.y1, (10-z), m, flag);
            xProductionRule(f.x2,f.y2, m, z);
        }
        m = incrementAngle(m);
        xProductionRule(f.x2,f.y2, m, z);
       }
   };
var drawShape = function(x, y, degrees) 
{
   xProductionRule(x, y, degrees, 0, 0);
};
drawShape(10, 380, 25);

Yor代码包含一个无限递归,因为xProductionRule无条件地调用自己。

要绘制分形,您必须限制递归的深度,或者防止渲染特定大小(如1像素)的零件。

我看到xProductionRule有5个参数,其中一个被称为nLevel,但该参数在任何地方都没有使用,事实上,您只使用4个参数来调用函数。我认为您应该使用该参数来限制递归的深度。在函数中添加一些check(nLevel < 7),并进行每次递归调用以包含nLevel+1作为参数。

在我看来,基于你提到的维基百科文章,你的代码骨架应该是这样的结构:

function drawA(depth, ... /* placement information */) {
    // here, draw the current branch
    // and then continue with it's children
    if (depth > 0) {
        drawA(depth - 1, ... /* derived placement information  */)
        drawB(depth - 1, ... /* another derived placement information  */)
    }
}
function drawB(depth, ... /* placement information */) {
    // here, draw the current branch
    // and then continue with it's children
    if (depth > 0) {
        drawA(depth - 1, ... /* derived placement information  */)
    }
}
drawA(7, ... /* placement of the root branch */)

我看不出有什么地方需要7圈。