Beispiel:Tanne.html

Aus SELFHTML-Wiki
Wechseln zu: Navigation, Suche
<!DOCTYPE html>
<html lang="de">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title></title>
		<style>
			canvas {
				display: block;
				margin: auto;
				height: 90vh;
				aspect-ratio: 0.7;
				border: thin solid black;
				border-radius: 1em;
				background-color: black;
			}
		</style>
		
		<script type="module">
			// Canvas und Grafikparameter
			const canvas = document.querySelector("canvas");
			const canvasHeight = canvas.height = canvas.clientHeight;
			const canvasWidth  = canvas.width  = canvas.clientWidth;
			const context = canvas.getContext("2d"); 
			const px0 = canvasWidth/2 ;
			const py0 = 15;
			const pxfak = canvasWidth/7;
			const pyfak = canvasHeight/12;

			// Punkt an (x,y) in der Farbe c setzen
			const punkt = function(x,y,c) {
				context.fillStyle = c;
				context.fillRect(x,canvasHeight-y,1,1);
			}

			// Nach https://en.wikipedia.org/wiki/Barnsley_fern
			const tannenbaumFunktion = function(xy) {
				const P1 = 0.01;
				const P2 = P1 + 0.85;
				const P3 = P2 + 0.07;
				const x = xy.x;
				const y = xy.y;
				const randomNumber = Math.random();
				if ( randomNumber < P1 ) {           //  1%
					xy.x = 0; 
					xy.y = .16*y; 
				}
				else if ( randomNumber < P2 ) {      // 85%
					xy.x =   .85*x; // + 0.04*y;
					xy.y = -0.04*x + 0.85*y + 1.6;
				}
				else if ( randomNumber < P3 ) {      //  7%
					xy.x = 0.20*x - 0.26*y; 
					xy.y = 0.23*x + 0.22*y + 0.44; //1.60; 
				}
				else {                               //  7%
					xy.x = -0.15*x + 0.28*y; 
					xy.y =  0.26*x + 0.24*y + 0.44; 
				}
				return xy;
			}

			// Startwert
			let xy = {x:1.0,y:1.0}; 

			// 100 Blindläufe zum Einschwingen
			for(var i=0;i<100;i++) xy = tannenbaumFunktion(xy); 

			// Aus 100 * Läufe Punkten wird ein Baum
			let Läufe = Math.ceil(canvasHeight/1);
			// setInterval damit es langsam läuft
			let interval = setInterval(() => {
				for(let i=0,px,py;i<100;i++) {
					xy = tannenbaumFunktion(xy);
					px = px0 + xy.x*pxfak;
					py = py0 + xy.y*pyfak;
					punkt(px,py,"#0f0");
				}
				Läufe--;
				if(Läufe==0) window.clearInterval(interval);
			},20);
		</script>

	</head>

	<body>
		<h1>Tannenbaum</h1>
		<p>Eine Modifikation des <a href="https://en.wikipedia.org/wiki/Barnsley_fern">Barnsley fern</a></p>
		<canvas></canvas>
	</body>
</html>