[js高手之路]html5 canvas动画教程 - 跟着鼠标移动消失的一堆炫彩小球
综合利用前面所学,实现一个绚丽的小球动画,这个实例用到的知识点,在我的博客全部都有,可以去这里查看所有的canvas教程
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 } 42 return false; 43 } 44 return true; 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 id="canvas" width="1200" height="600"></canvas> 79 </body>
作者:ghostwu, 出处:http://www.cnblogs.com/ghostwu
博客大多数文章均属原创,欢迎转载,且在文章页面明显位置给出原文连接