Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Дремин Рома #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions Lsystem.js
Original file line number Diff line number Diff line change
@@ -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;
}
105 changes: 7 additions & 98 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,108 +3,17 @@
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Cache-Control" content="no-cache"/>

<script src="Lsystem.js"></script>
<script>
//пример рисования произвольного множества точек
function example1() {
//получаем html-элемент типа canvas и его характеристики
var canvas = document.getElementById("canvas1");
var canvasHeight = parseInt(canvas.getAttribute("height"));
var canvasWidth = parseInt(canvas.getAttribute("width"));

//создаем 2d context
function run() {
var canvas = document.getElementById("mainCanvas");
canvas.setAttribute("Width", window.innerWidth);
canvas.setAttribute("Height", window.innerHeight);
var context = canvas.getContext('2d');

//создаем "буфер" imageData, в который будем класть новую информацию о цветах
var imageData = context.createImageData(canvasWidth, canvasHeight);
for (var i = 0; i < canvasWidth; i++) {
for (var j = 0; j < canvasHeight; j++) {
var red = 0;
var green = 0;
var blue = (i + j) % 255;
if (i % 20 == 0)
red = 150;
if (j % 20 == 0)
green = 150;
var opacity = 255;

imageData.data[4*(i + canvasWidth*j) + 0] = red;
imageData.data[4*(i + canvasWidth*j) + 1] = green;
imageData.data[4*(i + canvasWidth*j) + 2] = blue;
imageData.data[4*(i + canvasWidth*j) + 3] = opacity;
}
}
//заполненный "буфер" imageData передаем в context для вывода на экран
context.putImageData(imageData, 0, 0);
}

//пример рисования отдельных линий
function example2() {
//получаем html-элемент типа canvas и его характеристики
var canvas = document.getElementById("canvas2");
var canvasHeight = parseInt(canvas.getAttribute("height"));
var canvasWidth = parseInt(canvas.getAttribute("width"));

//создаем 2d context
var context = canvas.getContext('2d');

//задаем стиль линий
context.lineWidth = "5";
context.strokeStyle = "green";

//начинаем создание нового пути
context.beginPath();
//задаем начальную точку линии
context.moveTo(0, 75);
//задаем конечную точку линии и добавляем линию в путь
context.lineTo(150, 100);
//выводим путь на экран
context.stroke();
}

//пример рисования полилиний (сначала вычисляем точки, затем рисуем)
function example3() {
//получаем html-элемент типа canvas и его характеристики
var canvas = document.getElementById("canvas3");
var canvasHeight = parseInt(canvas.getAttribute("height"));
var canvasWidth = parseInt(canvas.getAttribute("width"));

//создаем 2d context
var context = canvas.getContext('2d');

//задаем стиль линий
context.lineWidth = "2";
context.strokeStyle = "#FF0000";

//создаем массив точек
//в качестве точек используются анонимные объекты со свойствами x и y
var points = [{x: 20, y: 50}, {x: 120, y: 50}, {x: 120, y: 100}, {x: 50, y: 20}];

//начинаем создание нового пути
context.beginPath();
//добавляем в путь все точки из массива
for (var i = 0; i < points.length; i++) {
var point = points[i];
if (i == 0)
context.moveTo(point.x, point.y);
else
context.lineTo(point.x, point.y);
}
//выводим путь на экран
context.stroke();
}

//вызывается после загрузки body
function run () {
example1();
example2();
example3();
drawFractal("snowflacke", context, {x: window.innerWidth / 3, y: window.innerHeight - 100, angle: 0 });
}
</script>

<body onload="run()">
<canvas height='200' width='200' id='canvas1'></canvas>
<canvas height='200' width='200' id='canvas2'></canvas>
<canvas height='200' width='200' id='canvas3'></canvas>
<canvas height='200' width='200' id='mainCanvas'></canvas>
</body>
</html>