1 <head> 2 <meta charset='utf-8' /> 3 <style> 4 #canvas { 5 border: 1px dashed #aaa; 6 } 7 </style> 8 <script src="./ball.js"></script> 9 <script> 10 window.onload = function () { 11 var oCanvas = document.querySelector("#canvas"), 12 oGc = oCanvas.getContext('2d'), 13 width = oCanvas.width, height = oCanvas.height, 14 balls = [], n = 50, gravity = 0.2; 15 function getRandColor() { 16 return '#' + (function (color) { 17 return (color += '0123456789abcdef'[Math.floor(Math.random() * 16)]) && (color.length == 6) ? color : arguments.callee(color); 18 })(''); 19 } 20 for (var i = 0; i < n; i++) { 21 var ball = new Ball(width / 2, height / 2, 20, getRandColor()); 22 ball.vx = (Math.random() * 2 - 1) * 5; 23 ball.vy = (Math.random() * 2 - 1) * 10; 24 balls.push(ball); 25 } 26 (function move() { 27 oGc.clearRect(0, 0, width, height); 28 balls.forEach(function (ball) { 29 if (ball.x < -ball.radius 30 || ball.x > width + ball.radius 31 || ball.y < -ball.radius 32 || ball.y > height + ball.radius) { 33 ball.x = width / 2; 34 ball.y = height / 2; 35 ball.vx = (Math.random() * 2 - 1) * 5; 36 ball.vy = (Math.random() * 2 - 1) * 10; 37 } 38 ball.x += ball.vx; 39 ball.y += ball.vy; 40 ball.vy += gravity; 41 ball.fill(oGc); 42 }); 43 requestAnimationFrame(move); 44 })(); 45 } 46 </script> 47 </head> 48 49 <body> 50 <canvas></canvas> 51 </body>
还可以通过控制小球的vx, vy,就是x方向和y方向的速度,来限制小球朝某一个方向发射,下面的例子,我们只让小球朝着x轴的右边发射
1 <head> 2 <meta charset='utf-8' /> 3 <style> 4 #canvas { 5 border: 1px dashed #aaa; 6 } 7 </style> 8 <script src="./ball.js"></script> 9 <script> 10 window.onload = function () { 11 var oCanvas = document.querySelector("#canvas"), 12 oGc = oCanvas.getContext('2d'), 13 width = oCanvas.width, height = oCanvas.height, 14 balls = [], n = 50; 15 function getRandColor() { 16 return '#' + ( function( color ){ 17 return ( color += '0123456789abcdef' [Math.floor( Math.random() * 16 )] ) && ( color.length == 6 ) ? color : arguments.callee( color ); 18 } )( '' ); 19 } 20 for( var i = 0; i < n; i++ ) { 21 var ball = new Ball( width / 2, height / 2, 20, getRandColor() ); 22 ball.vx = Math.abs( ( Math.random() * 2 - 1 ) * 5 ); 23 ball.vy = ( Math.random() * 2 - 1 ) * 5; 24 balls.push( ball ); 25 } 26 (function move(){ 27 oGc.clearRect( 0, 0, width, height ); 28 balls.forEach( function( ball ){ 29 if ( ball.x < -ball.radius 30 || ball.x > width + ball.radius 31 || ball.y < -ball.radius 32 || ball.y > height + ball.radius ) { 33 ball.x = width / 2; 34 ball.y = height / 2; 35 ball.vx = Math.abs( ( Math.random() * 2 - 1 ) * 5 ); 36 ball.vy = ( Math.random() * 2 - 1 ) * 5; 37 } 38 ball.x += ball.vx; 39 ball.y += ball.vy; 40 ball.fill( oGc ); 41 } ); 42 requestAnimationFrame( move ); 43 })(); 44 } 45 </script> 46 </head> 47 <body> 48 <canvas></canvas> 49 </body>