如何修改科赫雪花L-系统的公理与产生式实现随机绘制
随机科赫雪花的L-System修改方案
问题描述
我有一个绘制科赫雪花的函数,需要修改成绘制随机科赫雪花——在迭代过程的每一步,将构造三角形的新顶点向内或向外旋转即可实现。以下是我的绘制函数,请告诉我需要修改公理(axiom)和产生式(productions)的哪些部分:
function drawRdFractal() { const iterationsInput = document.getElementById("iterationsInput").value; const color = document.getElementById("colorPicker").value; const scaleInput = document.getElementById("scaleInput").value; const iterations = parseInt(iterationsInput); const scale = parseFloat(scaleInput); var canvas = document.querySelector('.myCanvas') var ctx = canvas.getContext("2d") ctx.strokeStyle = color; ctx.lineWidth = 2; const width = canvas.clientWidth; const height = canvas.clientHeight; ctx.clearRect(0, 0, width, height); ctx.translate(startGeneration.x, startGeneration.y); ctx.scale(scale, scale); console.log(scale + "- scale"); /* initialize a koch curve L-System that uses final functions to draw the fractal onto a Canvas element. F: draw a line with length relative to the current iteration (half the previous length for each step) and translates the current position to the end of the line +: rotates the canvas 60 degree -: rotates the canvas -60 degree */ var koch = new LSystem({ axiom: 'F++F++F', productions: {'F': 'F-F++F-F'}, finals: { '+': () => { ctx.rotate((Math.PI/180) * 60) }, '-': () => { ctx.rotate((Math.PI/180) * -60) }, 'F': () => { ctx.beginPath() ctx.moveTo(0,0) ctx.lineTo(0, 28) ctx.stroke() ctx.translate(0, 28) } } }) koch.iterate(iterations); koch.final(); }
修改方案
1. 公理(axiom)无需修改
原公理'F++F++F'定义了科赫雪花的初始等边三角形框架,随机化不需要改变这个基础结构。
2. 产生式(productions)核心修改
原版产生式是固定的向外凸起规则,要实现随机化,需要让每次替换F时随机选择向外凸起或向内凹陷的规则:
- 向外规则(原规则):
'F-F++F-F'(生成向外的三角形凸起) - 向内规则:
'F+F--F+F'(将原规则的-和+反转,生成向内的三角形凹陷)
修改后的产生式需要用函数返回随机结果,替换原固定字符串:
productions: { 'F': () => { // 随机选择向外或向内规则,可调整概率(比如0.5是各50%) return Math.random() > 0.5 ? 'F-F++F-F' : 'F+F--F+F'; } }
原理说明
+对应顺时针旋转60度,-对应逆时针旋转60度;- 向外规则通过
-和++的组合,在直线段中间生成向外的三角形; - 向内规则通过
+和--的组合,在直线段中间生成向内的三角形; - 每次迭代时随机选择两种规则,就能生成不规则的随机科赫雪花效果。
内容的提问来源于stack exchange,提问作者Roman Soroka
相关产品推荐
相关产品推荐

