Die Koch-Kurve
Passend zur Saison habe ich die fraktale "Schneeflocke" von Helge Koch in JavaScript implementiert.
Das Script dazu
const animation = {
level: -1,
step: 1,
generate: function( ctx, level, sx, sy, ex, ey )
{
// Terminate the recursion
if( level == 0 )
{
ctx.lineTo( ex, ey ) ;
}
else
{
// Compute the intermediate points
let rex = sx + (ex - sx) / 3 ;
let rey = sy + (ey - sy) / 3 ;
let rsx = ex - (ex - sx) / 3 ;
let rsy = ey - (ey - sy) / 3 ;
let px = (rsx + rex) / 2 + 0.866 * (rey - rsy) ;
let py = (rsy + rey) / 2 - 0.866 * (rex - rsx) ;
// Draw the segments recursively
this.generate( ctx, level-1, sx, sy, rex, rey ) ;
this.generate( ctx, level-1, rex, rey, px, py ) ;
this.generate( ctx, level-1, px, py, rsx, rsy ) ;
this.generate( ctx, level-1, rsx, rsy, ex, ey ) ;
}
},
draw: function()
{
// Get the graphics context
const canvas = document.getElementById( "canvas" ) ;
const ctx = canvas.getContext( "2d" ) ;
// Adjust the level
this.level = this.level + this.step ;
if( this.level == 0 )
this.step = 1 ;
if( this.level == 6 )
this.step = -1 ;
// Clear the background
ctx.fillStyle = "#C0C0C0" ;
ctx.fillRect( 0, 0, 600, 700 ) ;
// Draw the snowflake
ctx.beginPath() ;
ctx.moveTo( 4, 516 )
this.generate( ctx, this.level, 4, 516, 595, 516 ) ;
this.generate( ctx, this.level, 595, 516, 300, 4 ) ;
this.generate( ctx, this.level, 300, 4, 4, 516 ) ;
ctx.fillStyle = "#FFFFFF" ;
ctx.fill() ;
ctx.stroke() ;
}
}
window.addEventListener( "load", event => {
const draw = animation.draw.bind( animation ) ;
draw() ;
setInterval( draw, 1200 ) ;
} ) ;