Koch snowflake
by Julien Roche
HTML
<canvas></canvas>
CSS
html, body {
margin: 0 0 0 0;
padding: 0 0 0 0;
border: none;
height: 100%;
width: 100%;
}
JavaScript
const canvasElement = document.querySelector('canvas');
const ctx = canvasElement.getContext('2d');
const part = 3;
function resize() {
canvasElement.height = window.innerHeight;
canvasElement.width = window.innerWidth;
}
function rotate(width, height, degree) {
const rotateFromDegreeTpRadian = degree * Math.PI / 180;
ctx.translate(width / 2, height / 2);
ctx.rotate(rotateFromDegreeTpRadian);
ctx.translate(width / -2, height / -2);
}
function calculateAngle(width, height) {
return Math.atan(width / height) * 180 / Math.PI;
}
function drawTriangles() {
const height = Math.floor(canvasElement.height / part);
const width = Math.floor(canvasElement.width / part);
drawTriangle(width, height, 0);
ctx.translate(width + (width / part), height);
ctx.fillStyle = 'red'
drawTriangle(width / part, height / part, 0/*90 - calculateAngle(width / 2, height)*/);
}
function drawTriangle(width, height, degree) {
ctx.save();
rotate(width * part, height * part, degree);
ctx.beginPath();
ctx.translate(width, 2 * height);
ctx.moveTo(0, 0);
ctx.lineTo(width, 0);
ctx.lineTo(width / 2, -height);
ctx.closePath();
ctx.fill();
ctx.restore();
}
function refresh() {
resize();
drawTriangles();
}
refresh();
const resizeObserver = new ResizeObserver(refresh);
resizeObserver.observe(document.body);