<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>canvas</title> <style type="text/css"> #canvas{ background-color: #eeeeee; } </style> </head> <body> <canvas id="canvas" width="500" height="500"></canvas> <script type="text/javascript"> window.onload = function(){ var canvas = document.getElementById("canvas"); var cobj = canvas.getContext("2d"); var arr = []; for(var i=0; i<8; i++){ var arrObj = { r: 15+5*Math.random(), x_3d: -200+i*30, y_3d: -100+200*Math.random(), z_3d: i*10, z_speed: 5+10*Math.random() } arr.push(arrObj); } var focusLen = 300; cobj.translate(250,250); setInterval(function(){ cobj.clearRect(-250,-250,500,500); var newarr = arr.sort(function(a,b){ return a.z_3d<b.z_3d; }); for(var i=0; i<newarr.length; i++){ arr[i].z_3d += arr[i].z_speed; if(arr[i].z_3d>600 || arr[i].z_3d<=-50){ arr[i].z_speed*=-1; } var scales = focusLen/(focusLen+arr[i].z_3d); var x = arr[i].x_3d*scales; var y = arr[i].y_3d*scales; cobj.save(); cobj.translate(x,y); cobj.scale(scales,scales); cobj.beginPath(); var colorObj = cobj.createRadialGradient(3,3,0,0,0,15); colorObj.addColorStop(0,"#cbc0f3"); colorObj.addColorStop(1,"#06198b"); cobj.fillStyle = colorObj; cobj.arc(0,0,15,0,2*Math.PI); cobj.fill(); cobj.restore(); } },50); } </script> </body> </html>
时间: 2024-11-05 06:12:47