×ÛºÏÀûÓÃÇ°ÃæËùѧ£¬ÊµÏÖÒ»¸öѤÀöµÄСÇò¶¯»£¬Õâ¸öʵÀýÓõ½µÄ֪ʶµã£¬ÔÚÎҵIJ©¿ÍÈ«²¿¶¼ÓÐ
1 <head> 2 <meta charset='utf-8' /> 3 <title>canvasìŲÊСÇò - By ghostwu</title> 4 <style> 5 #canvas { 6 border: 1px dashed #aaa; 7 } 8 </style> 9 <script> 10 function Ball(x, y, r, color) { 11 this.x = x || 0; 12 this.y = y || 0; 13 this.radius = r || 20; 14 this.color = color || '#09f'; 15 } 16 Ball.prototype = { 17 constructor: Ball, 18 stroke: function (cxt) { 19 cxt.strokeStyle = this.color; 20 cxt.beginPath(); 21 cxt.arc(this.x, this.y, this.radius, 0, 2 * Math.PI); 22 cxt.closePath(); 23 cxt.stroke(); 24 }, 25 fill: function (cxt) { 26 cxt.fillStyle = this.color; 27 cxt.beginPath(); 28 cxt.arc(this.x, this.y, this.radius, 0, 2 * Math.PI); 29 cxt.closePath(); 30 cxt.fill(); 31 }, 32 update : function( balls ){ 33 this.x += this.vx; 34 this.y += this.vy; 35 this.radius--; 36 if ( this.radius < 0 ) { 37 for( var i = 0; i < balls.length; i++ ){ 38 if( balls[i] == this ) { 39 balls.splice( i, 1 ); 40 } 41 } ; 43 } ; 45 } 46 } 47 </script> 48 <script> 49 window.onload = function () { 50 var oCanvas = document.querySelector("#canvas"), 51 oGc = oCanvas.getContext('2d'), 52 width = oCanvas.width, height = oCanvas.height, 53 balls = [], n = 50; 54 function getRandColor() { 55 return '#' + (function (color) { 56 return (color += '0123456789abcdef'[Math.floor(Math.random() * 16)]) && (color.length == 6) ? color : arguments.callee(color); 57 })(''); 58 } 59 oCanvas.addEventListener( 'mousemove', function( ev ){ 60 var oEvent = ev || event; 61 var ball = new Ball( oEvent.clientX, oEvent.clientY, 30, getRandColor()); 62 ball.vx = (Math.random() * 2 - 1) * 5; 63 ball.vy = (Math.random() * 2 - 1) * 5; 64 balls.push( ball ); 65 }, false ); 66 67 ( function move(){ 68 oGc.clearRect( 0, 0, width, height ); 69 for( var i = 0; i < balls.length; i++ ){ 70 balls[i].update( balls ) && balls[i].fill( oGc ); 71 } 72 requestAnimationFrame( move ); 73 } )(); 74 } 75 </script> 76 </head> 77 <body> 78 <canvas></canvas> 79 </body>
run code
¡¡