From ff799bbc2182b636e017573665e5c676cd256e61 Mon Sep 17 00:00:00 2001 From: Kostas Date: Thu, 21 Jun 2018 02:59:32 +0500 Subject: [PATCH 1/2] New solution --- index.html | 126 +++++++++-------------------------------------------- index.js | 77 ++++++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+), 106 deletions(-) create mode 100644 index.js diff --git a/index.html b/index.html index 39a9d04..0177dfe 100644 --- a/index.html +++ b/index.html @@ -1,110 +1,24 @@ - - + + + - - - - + + Koch Snowflake + - - - - + + + +
+ + \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..ecc3674 --- /dev/null +++ b/index.js @@ -0,0 +1,77 @@ +(function() { + var canvas = document.createElement('canvas'); + document.getElementById('canvas').appendChild(canvas); + + var context = canvas.getContext('2d'); + var width = canvas.width = 420; + var height = canvas.height = 420; + + p1: { + x: 0, + y: -150 + }, + p2: { + x: 150, + y: 100 + }, + p3: { + x: -150, + y: 100 + } + + }; + context.translate(.5 * width, .5 * height); + + var koch = function koch(a, b) { + var n = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 3; + var dx = b.x - a.x, + dy = b.y - a.y; + + var dist = Math.sqrt(dx * dx + dy * dy); + var unit = dist / 3; + var angle = Math.atan2(dy, dx); + + var p1 = { + x: a.x + dx / 3, + y: a.y + dy / 3 + }; + var p3 = { + x: b.x - dx / 3, + y: b.y - dy / 3 + }; + var p2 = { + x: p1.x + Math.cos(angle - Math.PI / 3) * unit, + y: p1.y + Math.sin(angle - Math.PI / 3) * unit + }; + + if (n > 0) { + koch(a, p1, n - 1); + koch(p1, p2, n - 1); + koch(p2, p3, n - 1); + koch(p3, b, n - 1); + } else { + context.beginPath(); + context.moveTo(a.x, a.y); + context.lineTo(p1.x, p1.y); + context.lineTo(p2.x, p2.y); + context.lineTo(p3.x, p3.y); + context.lineTo(b.x, b.y); + context.stroke(); + } + }; + + koch(startingPoints.p1, startingPoints.p2, 5); + koch(startingPoints.p2, startingPoints.p3, 5); + koch(startingPoints.p3, startingPoints.p1, 5); + + var input = document.getElementById('recursion'); + + input.onchange = function() { + var n = input.options[input.selectedIndex].value; + context.clearRect(-width / 2, height / -2, width, height); + + koch(startingPoints.p1, startingPoints.p2, n); + koch(startingPoints.p2, startingPoints.p3, n); + koch(startingPoints.p3, startingPoints.p1, n); + }; +})(); From d19b5332689d81225a98408ed09bc53de1dce6d8 Mon Sep 17 00:00:00 2001 From: Koroshef Konstantin Date: Fri, 22 Jun 2018 00:26:18 +0500 Subject: [PATCH 2/2] Fix --- index.js | 1 + 1 file changed, 1 insertion(+) diff --git a/index.js b/index.js index ecc3674..577f368 100644 --- a/index.js +++ b/index.js @@ -6,6 +6,7 @@ var width = canvas.width = 420; var height = canvas.height = 420; + var startingPoints = { p1: { x: 0, y: -150