我试图在处理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);发布于 2015-12-19 11:48:45
Yor代码包含一个不确定的递归,xProductionRule无条件地调用它自己。
要绘制分形,您必须限制递归的深度,或者阻止在特定大小(如1像素)下绘制部件。
我看到xProductionRule有5个参数,其中一个名为nLevel,但该参数在任何地方都没有使用,实际上,您只使用4个参数调用函数。我认为你应该用这个论点来限制递归的深度。向函数添加一些check (nLevel < 7),并进行每次递归调用,将nLevel+1作为参数。
在我看来,基于您提到的wikipedia文章,您的代码框架应该构建如下所示:
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圈的地方。
https://stackoverflow.com/questions/34370297
复制相似问题