绘制随机科赫雪花的函数

问题描述 投票:0回答:1

我有一个函数,可以绘制科赫雪花,但我必须更改它以绘制随机科赫雪花,这意味着:要获得它,在迭代过程的每一步向内或向外旋转新顶点就足够了 所构建的三角形。这是一个示例,它应该是什么样子randomized koch snowflake

这是我绘制科赫雪花的函数,请告诉我应该在公理和产品中更改哪些内容

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

}

javascript fractals l-systems
1个回答
0
投票

更改后分形看起来像that,但它看起来仍然不像我想要的,请帮忙))) 现在我的代码看起来像这样

    var koch = new LSystem({
    axiom: 'F--F--F',
    productions: {'F': () => Math.random() >= 0.5 ? 'F-F++F-F' : 'F+F--F+F'},
    finals: {
        rand_value: 0, // Додати поле для збереження кута
        '+': function() {
            this.rand_value = (Math.PI / 180) * 60; 
            ctx.rotate(this.rand_value);
        },
        '-': function() {
            ctx.rotate(0-this.rand_value); // Використати збережений кут
        },
        'F': () => {
            ctx.beginPath()
            ctx.moveTo(0,0)
            ctx.lineTo(0, 28)
            ctx.stroke()
            ctx.translate(0, 28)
        }
    }
});


koch.iterate(iterations);
koch.final();
© www.soinside.com 2019 - 2024. All rights reserved.