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

Сатин Н.А. #4

Open
wants to merge 2 commits 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
85 changes: 85 additions & 0 deletions DragonFractal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
class Pixels {

constructor() {
this.pixelsCollection = [];
}

setPixels(x, y) {
this.pixelsCollection.push({ x: x, y: y });
}

drawDragonFractal(image, size) {
if (this.pixelsCollection.length === 0) return;
const maxX = this.max((p) => p.x);
const maxY = this.max((p) => p.y);
const minX = this.min((p) => p.x);
const minY = this.min((p) => p.y);
const width = maxX - minX;
const height = maxY - minY;
const scaleX = (image.width - 20) / width;
const scaleY = (image.height - 20) / height;
const scale = Math.min(scaleX, scaleY);
for (let pixel of this.pixelsCollection) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Цикле for of можно const pixel.

let x = (pixel.x - minX - width / 2) * scale + image.width / 2.0;
let y = (pixel.y - minY - height / 2) * scale + image.height / 2.0;
x = Math.ceil(x);
y = Math.ceil(y);
this.putColor(image, x, y, size.width);
}
return image;
}

setPixel(x, y) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Более правильно - addPixel

this.pixelsCollection.push({ x: x, y: y });
}

putColor(image, x, y, width) {
image.data[4 * (x + width * y) + 0] = 125;
image.data[4 * (x + width * y) + 1] = 125;
image.data[4 * (x + width * y) + 2] = 125;
image.data[4 * (x + width * y) + 3] = 255;
return image;
}

max(selector) {
let max = Number.MIN_SAFE_INTEGER;
for (let pixel of this.pixelsCollection) {
let element = selector(pixel);
if (element > max) {
max = element;
}
}
return max;
}

min(selector) {
let min = Number.MAX_SAFE_INTEGER;
for (let pixel of this.pixelsCollection) {
if (selector(pixel) < min) {
min = selector(pixel);
}
}
return min;
}
}

function getDragonFractal(image, size) {
const iterCount = 100000;
let x = 1.0;
let x1 = 0.0;
let y = 0.0;
let y1 = 0.0;
const angle45 = Math.PI / 4;
const pixels = new Pixels();
for (let i = 0; i < iterCount; i++) {
const rnd = Math.random() > 0.5 ? 1 : 0;
x1 = (x * Math.cos(angle45 + Math.PI / 2 * rnd)
- y * Math.sin(angle45 + Math.PI / 2 * rnd)) / Math.sqrt(2) + 1 * rnd;
y1 = (x * Math.sin(angle45 + Math.PI / 2 * rnd)
+ y * Math.cos(angle45 + Math.PI / 2 * rnd)) / Math.sqrt(2);
x = x1;
y = y1;
pixels.setPixel(x, y);
}
return pixels.drawDragonFractal(image, size);
}
128 changes: 23 additions & 105 deletions index.html
Original file line number Diff line number Diff line change
@@ -1,110 +1,28 @@
<!doctype html>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Cache-Control" content="no-cache"/>

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

//создаем 2d context
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();
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Cache-Control" content="no-cache" />
<script type="text/javascript" src="DragonFractal.js"></script>
<script>
function example1() {
var canvas = document.getElementById("canvas1");
var canvasHeight = parseInt(canvas.getAttribute("height"));
var canvasWidth = parseInt(canvas.getAttribute("width"));
var context = canvas.getContext('2d');
var imageData = context.createImageData(canvasWidth, canvasHeight);
var size = { width: canvasWidth, height: canvasHeight };
context.putImageData(getDragonFractal(imageData, size), 0, 0);
}
function run() {
example1();
}
</script>

<body onload="run()">
<canvas height='400' width='400' id='canvas1'></canvas>

</body>

<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>
</html>