标签:style blog http io color os ar java for
预览地址->mycircle
应该是最简单的canvas动画的制作,主要难点是画布的旋转,这里要用到save和restore方法。主要思路是画出一个圆,然后旋转画布,递增坐标,产生动的效果。
碰撞后的轨迹没有进行计算。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <script type="text/javascript"> 5 window.onload = function() { 6 var canvas = document.getElementById(‘myCanvas‘); 7 var c = canvas.getContext(‘2d‘); 8 9 var len = 0; 10 var r = 30; 11 var x = []; 12 var y = []; 13 var deg = []; 14 var addx = []; 15 var addy = []; 16 var adddeg = []; 17 var allcolor = []; 18 19 getCircle(); 20 document.getElementById(‘btn‘).addEventListener(‘click‘, getCircle); 21 window.setInterval(function() {gameStart();}, 1); 22 23 function getCircle() { 24 len++; 25 x.push(35); 26 y.push(35); 27 addx.push(1); 28 addy.push(1); 29 adddeg.push(1); 30 deg.push(0); 31 allcolor.push(getGrd()); 32 } 33 34 function gameStart() { 35 c.clearRect(0, 0, 1000, 500); 36 for(var i = 0; i < len; i++) { 37 moving(i); 38 } 39 judge(); 40 } 41 42 function moving(i) { 43 if(x[i] + 35 > 1000 || x[i] - 35 < 0) { 44 addx[i] *= -1, adddeg[i] *= -1; 45 } 46 47 if(y[i] + 35 > 500 || y[i] - 35 < 0) { 48 addy[i] *= -1, adddeg[i] *= -1; 49 } 50 51 c.save(); 52 c.translate(x[i], y[i]); 53 c.rotate(deg[i] * Math.PI / 180); 54 c.strokeStyle = allcolor[i]; 55 c.beginPath(); 56 c.arc(0, 0, r, 0, Math.PI * 2, true); 57 c.lineWidth = 5; 58 c.stroke(); 59 x[i] += addx[i], y[i] += addy[i], deg[i] += adddeg[i]; 60 c.restore(); 61 } 62 63 function judge() { 64 for(var i = 0; i < len; i++) 65 for(var j = i + 1; j < len; j++) { 66 if(getDis(x[i], y[i], x[j], y[j]) <= r * 2) { 67 addx[i] *= -1, addy[i] *= -1, adddeg[i] *= -1; 68 addx[j] *= -1, addy[j] *= -1, adddeg[j] *= -1; 69 } 70 } 71 } 72 73 function getRandomColor() { 74 while(true) { 75 var a = Math.random(); 76 // case 77 if(a < 0.2) continue; 78 var mycolor = ‘#‘ + parseInt(a * 0xffffff).toString(16); 79 return mycolor; 80 } 81 } 82 83 function getGrd() { 84 var grd = c.createLinearGradient(-r, -r, r, r); 85 grd.addColorStop(0, getRandomColor()); 86 grd.addColorStop(0.2, getRandomColor()); 87 grd.addColorStop(0.4, getRandomColor()); 88 grd.addColorStop(0.6, getRandomColor()); 89 grd.addColorStop(0.8, getRandomColor()); 90 grd.addColorStop(1, getRandomColor()); 91 return grd; 92 } 93 94 function getDis(x1, y1, x2, y2) { 95 var res = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); 96 return Math.sqrt(res); 97 } 98 }; 99 </script> 100 </head> 101 102 <body> 103 <canvas id=‘myCanvas‘ width=1000 height=500 style=‘background-color:black‘> 104 </canvas> 105 <input type=‘button‘ value=‘add‘ id=‘btn‘ /> 106 </body> 107 </html>
这里有几个case要解释。
标签:style blog http io color os ar java for
原文地址:http://www.cnblogs.com/bigbigsunrise/p/4067049.html