Created
April 30, 2024 07:44
-
-
Save olecksamdr/8a63ae519a8c2d0a972951c07630b24f to your computer and use it in GitHub Desktop.
Fractal Tree on HTML Canvas
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
const canvas = document.getElementById('canvas') | |
const ctx = canvas.getContext('2d') | |
canvas.width = window.innerWidth | |
canvas.height = window.innerHeight | |
const { width, height } = canvas | |
const startX = width / 2 | |
const startY = height - 100 | |
let angle = 45 * Math.PI / 180 | |
function modulusOfAVector({x, y}) { | |
return Math.sqrt(x**2 + y**2) | |
} | |
canvas.addEventListener('pointermove', function({ clientX, clientY }) { | |
requestAnimationFrame(() => { | |
const mouseVec = { x: clientX - startX, y: clientY - startY } | |
angle = Math.acos(-mouseVec.y / modulusOfAVector(mouseVec)) | |
ctx.clearRect(0, 0, width, height) | |
ctx.save() | |
ctx.translate(width / 2, height) | |
branch(100, angle, ctx) | |
ctx.restore() | |
}) | |
}) | |
function branch(len, angle, ctx) { | |
if (len > 5) { | |
ctx.beginPath() | |
ctx.moveTo(0, 0) | |
ctx.lineTo(0, -len) | |
ctx.stroke() | |
ctx.translate(0, -len) | |
ctx.save() | |
ctx.rotate(angle) | |
branch(len * 0.7, angle, ctx) | |
ctx.restore() | |
ctx.save() | |
ctx.rotate(-angle) | |
branch(len * 0.7, angle, ctx) | |
ctx.restore() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment