Last active
February 4, 2021 18:09
-
-
Save rozag/2e6831aa2a5de7c24d68 to your computer and use it in GitHub Desktop.
Простой фрактал на JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head lang="en"> | |
<meta charset="UTF-8"> | |
<title>SimpleFractal</title> | |
</head> | |
<body> | |
<canvas width="900" height="600"></canvas> | |
</body> | |
<script src="main.js"></script> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
var context = document.querySelector("canvas").getContext("2d"); | |
function branch(length, angle, scale) { | |
context.fillRect(0, 0, 1, length); // Рисуем "ствол-корень" дерева | |
var MIN_LENGTH = 8; | |
if (length < MIN_LENGTH) // Обрываем рекурсию, когда линии становятся слишком короткими | |
return; | |
context.save(); // Сохраняем текущее состояние системы координат | |
context.translate(0, length); // Сдвигаем "курсор" в конец "ствола-корня" | |
context.rotate(-angle); // Поворачиваем систему координат на какой-то угол влево | |
branch(length * scale, angle, scale); // Рекурсивно рисуем левую ветвь | |
context.rotate(2 * angle); // Поворачиваем систему координат на симметричный угол вправо | |
branch(length * scale, angle, scale); // Рекурсивно рисуем правую ветвь | |
context.restore(); // Восстанавливаем начальное состояние системы координат | |
} | |
context.translate(document.querySelector("canvas").clientWidth / 2, 0); // Начальный сдвиг системы координат, | |
// чтобы центрировать дерево | |
branch(90, 0.5, 0.75); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment