Kode Animasi HTML5 Canvas Dots and Lines
Salah satu kegunaan pemanfaatan HTML5 Canvas, dapat digunakan untuk membuat animasi atau wallpaper seperti gambar di atas.
Berikut ini adalah contoh kode HTML5 yang penulis buat sebagai percobaan untuk tema 'generate wallpaper' menggunakan kode program Javascript:
<html> <head> <title>Dots and Lines Animation</title> </head> <body> <canvas id="myCanvas" width="1024" height="768"> </canvas> <script> var canvas = document.getElementById("myCanvas"); var num=25; var points=[]; for(i=0;i<2*num;i++){ points[4*i+0]=Math.random() * canvas.width; points[4*i+1]=Math.random() * canvas.height; points[4*i+2]=-2+Math.random() *5; points[4*i+3]=-2+Math.random() *5; if(points[4*i+2]==0 && points[4*i+3]==0)points[4*i+2]=1; } function Menggambar() { var ctx = canvas.getContext("2d"); ctx.fillStyle = "black"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.globalAlpha = 0.2; for(i=0;i<num;i++){ points[4*i+0]+=points[4*i+2]; points[4*i+1]+=points[4*i+3]; if(points[4*i+0]>canvas.width+10)points[4*i+0]=-5; else if(points[4*i+0]<-10)points[4*i+0]=canvas.width+5; if(points[4*i+1]>canvas.height+10)points[4*i+1]=-5; else if(points[4*i+1]<-10)points[4*i+1]=canvas.height+5; ctx.fillStyle = "yellow"; ctx.beginPath(); ctx.arc(points[4*i+0],points[4*i+1],5, 0, 2 * Math.PI, true); ctx.fill(); for(j=i+1;j<num;j++){ var rx=points[4*j+0]-points[4*i+0]; var ry=points[4*j+1]-points[4*i+1]; var r=Math.sqrt(rx*rx+ry*ry); if(r<200){ ctx.strokeStyle = "yellow"; ctx.beginPath(); ctx.moveTo(points[4*i+0],points[4*i+1]); ctx.lineTo(points[4*j+0],points[4*j+1]); ctx.lineWidth = 1; ctx.stroke(); } } } ctx.globalAlpha = 1.0; for(i=num;i<2*num;i++){ points[4*i+0]+=points[4*i+2]; points[4*i+1]+=points[4*i+3]; if(points[4*i+0]>canvas.width+10)points[4*i+0]=-5; else if(points[4*i+0]<-10)points[4*i+0]=canvas.width+5; if(points[4*i+1]>canvas.height+10)points[4*i+1]=-5; else if(points[4*i+1]<-10)points[4*i+1]=canvas.height+5; ctx.fillStyle = "white"; ctx.beginPath(); ctx.arc(points[4*i+0],points[4*i+1],5, 0, 2 * Math.PI, true); ctx.fill(); for(j=i+1;j<2*num;j++){ var rx=points[4*j+0]-points[4*i+0]; var ry=points[4*j+1]-points[4*i+1]; var r=Math.sqrt(rx*rx+ry*ry); if(r<200){ ctx.strokeStyle = "white"; ctx.beginPath(); ctx.moveTo(points[4*i+0],points[4*i+1]); ctx.lineTo(points[4*j+0],points[4*j+1]); ctx.lineWidth = 1; ctx.stroke(); } } } window.requestAnimationFrame(Menggambar); } Menggambar(); </script> </body> </html>
Komentar
Posting Komentar