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

Сатин Н.А, #3

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
107 changes: 9 additions & 98 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,108 +3,19 @@
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Cache-Control" content="no-cache"/>

<script type = "text/javascript" src = "src/FractalDrawer.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 drawBush() {
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("bush", 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>
<body onload="drawBush()" onresize="drawBush()">
<canvas height='2000' width='2000' id='mainCanvas'></canvas>
</body>
</html>
81 changes: 81 additions & 0 deletions src/FractalDrawer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
class LSystem {

/**
*
* @param {String} axiom - axiom of LSystem
* @param {object} rule - Dictionary [char] => newChar
*/

constructor(axiom, rule) {
this.axiom = axiom;
this.rule = rule;
}

/**
*
* @param {number} depth - recursion depth
* @returns {String} - array of symbols
*/

buildSequence(depth) {
if (depth < 1)
throw new RangeError("Depth can't be less then 1");

let result = this.axiom;
for (let i = 0; i < depth; i++) {
let newSequence = "";
for (let j = 0; j < result.length; j++) {
if (this.rule[result[j]] === undefined)
newSequence += result[j];
else
newSequence += this.rule[result[j]];
}
result = newSequence;
}
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();
switch(fractal) {
case "bush":
drawShape(startPos, context, {system : bush, depth : 5, length : 10, angle : Math.PI/8})
break;
case "snowflacke":
drawShape(startPos, context, {system : snowflacke, depth : 3, length : 3, angle : Math.PI/3})
break;
default:
throw new RangeError("Unknow fractal type");
}
context.stroke();
}

function drawShape(position, context, shape) {
const sequence = shape.system.buildSequence(shape.depth);
const actions = buildActionsDictionary(context, position, shape.length, shape.angle);
for (let i = 0; i < sequence.length; i++) {
if (actions[sequence[i]] != undefined)
actions[sequence[i]]();
}
}

function buildActionsDictionary(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;
}