Canvas mit JavaScript
Submitted by Erik Wegner
on
Body
Canvas stellt die Möglichkeit bereit, mit JavaScript zur Laufzeit Bilder und Animationen auf einer Webseite zu erzeugen. In diesem Beispiel wird eine Sinus-Welle angezeigt.
Demo
Quellcode
<!DOCTYPE html> <html><head><title>Canvas demo</title></head> <body> <canvas id="canvas1" width="100" height="50">C A N V A S</canvas> <script type="text/javascript"> if ( window.addEventListener ) { addEventListener( "load", draw, false ); } else { attachEvent( "onload", draw ); } var width = 0; var height = 0; var amplitude = 0; var deg = 0; var deginc = 1; var starty = 0; var stretch = 1.3; function draw(){ prepare(); window.setInterval(timerEvent, 66); } function prepare() { var canvas = document.getElementById('canvas1'); if (canvas) { width = canvas.width; height = canvas.height; amplitude = height / 2 - 3; starty = height / 2; } } function timerEvent() { var canvas = document.getElementById('canvas1'); if (canvas.getContext) { canvas = canvas.getContext('2d'); //canvas.fillStyle = "rgb(255,255,255)"; //canvas.fillRect( 0, 0, width, height); canvas.clearRect(0, 0, width, height); // Create gradient var grd=canvas.createLinearGradient(0,0,width,0); grd.addColorStop(0,"white"); grd.addColorStop(0.1,"red"); grd.addColorStop(0.9,"red"); grd.addColorStop(1,"white"); // Fill with gradient canvas.strokeStyle=grd; canvas.lineWidth = 5; canvas.fillStyle = "rgb(250,0,0)"; canvas.beginPath(); canvas.moveTo(0, starty); starty = height / 2 + Math.sin((deg + deginc) * 6.28 / width / stretch) * amplitude; for (x = 0; x < width; x += 2) { var y = height / 2 + Math.sin((deg + x) * 6.28 / width / stretch) * amplitude; canvas.lineTo(x,y); } canvas.stroke(); } deg+=deginc; while(deg > width * stretch) deg -= width * stretch; } </script> </body> </html>