From 00fea7c038bebaf1e8c9293f07d99d22f77185f2 Mon Sep 17 00:00:00 2001 From: Dremin Roman Date: Wed, 31 Oct 2018 16:20:09 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D1=80=D0=B5=D0=BC=D0=B8=D0=BD=20=D0=A0?= =?UTF-8?q?=D0=BE=D0=BC=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lsystem.js | 60 ++++++++++++++++++++++++++++++ index.html | 105 ++++------------------------------------------------- 2 files changed, 67 insertions(+), 98 deletions(-) create mode 100644 Lsystem.js diff --git a/Lsystem.js b/Lsystem.js new file mode 100644 index 0000000..a7642d2 --- /dev/null +++ b/Lsystem.js @@ -0,0 +1,60 @@ +class LSystem { + +constructor(axiom, rule) { + this.axiom = axiom; + this.rule = rule; +} +buildSequence(depth) { + let result = this.axiom; + for (let i = 0; i < depth; i++) { + let sequence1 = ""; + for (let j = 0; j < result.length; j++) { + if (this.rule[result[j]] === undefined) + sequence1 += result[j]; + else + sequence1 += this.rule[result[j]]; + } + result = sequence1; + } + return result; +} +} + +const snowflacke = new LSystem("[F]+[F]+[F]+[F]+[F]+[F]", {"F" : "F[+FF][-FF]FF[+F][-F]FF"}); +const bush = new LSystem("F", {"F" : "-F+F+[+F-F-]-[-F+F+F]"}); +function drawFractal(fractal, context, startPos) { +context.beginPath(); +if(fractal == "bush") { + drawFigure(startPos, context, {system : bush, depth : 5, length : 10, angle : Math.PI/8}) +} +else{ + drawFigure(startPos, context, {system : snowflacke, depth : 3, length : 3, angle : Math.PI/3}) +} +context.stroke(); +} + +function drawFigure(position, context, figure) { + const sequence = figure.system.buildSequence(figure.depth); + const actions = buidRulesRunner(context, position, figure.length, figure.angle); + for (let i = 0; i < sequence.length; i++) { + if (actions[sequence[i]] != undefined) + actions[sequence[i]](); + } +} + +function buidRulesRunner(drawingContext, startPos, length, angle) { +let position = startPos; +let stack = []; +let alphabet = {}; +alphabet['F'] = () => { + drawingContext.moveTo(position.x, position.y); + position.x += Math.cos(position.angle) * length; + position.y += Math.sin(position.angle) * length; + drawingContext.lineTo(position.x, position.y); +} +alphabet['+'] = () => position.angle += angle; +alphabet['-'] = () => position.angle -= angle; +alphabet['['] = () => stack.push({x: position.x, y:position.y, angle: position.angle }); +alphabet[']'] = () => position = stack.pop(); +return alphabet; +} \ No newline at end of file diff --git a/index.html b/index.html index 39a9d04..9c1486d 100644 --- a/index.html +++ b/index.html @@ -3,108 +3,17 @@ - + - - - - + \ No newline at end of file