效果请看:
http://keleyi.com/a/bjad/p9exlcwi.htm
请使用支持HTML5的浏览器查看效果。
以下是代码:
3 <html> 4 <body> 5 <canvas width="300" height="300" id="keleyieye" style="background:black"></canvas> 6 </body> 7 </html> 8 <script> 9 10 var keleyieye = document.getElementById(‘keleyieye‘); 11 var graphics = keleyieye.getContext(‘2d‘); 12 var centerX = keleyieye.width/2; 13 var centerY = keleyieye.height/2; 14 //设置角度值,同时也就眼睛的横坐标长度 15 var angle = 300; 16 //因为眨眼采用的sin()函数组成,所以其自然有幅值这一个属性。 17 var amplitude = 30; 18 //创建一个用于保存幅值的变化的变量,采用amplitude的缩写ampl,便于认识 ^_^ 19 var ampl = 20; 20 //灰眼球的半径 21 var blackBallSemi = 25; 22 var flag = true; 23 24 function paint() { 25 if (flag) { 26 ampl++; 27 if (ampl >= amplitude) { 28 flag = false; 29 } 30 }else { 31 ampl--; 32 if (ampl <= 0) { 33 flag = true; 34 } 35 } 36 //以centerX,centerY为中心,在眼睛所在的地方绘制一个白色的背景底色, 37 //长度为angle,宽为amplitude*2 38 39 graphics.fillStyle="white"; 40 41 graphics.fillRect(centerX-angle/2, centerY-amplitude, angle, amplitude*2); 42 43 //以centerX,centerY为中心,绘制一个灰色的眼球 44 //半径为blackBallSemi*2 45 graphics.beginPath(); 46 graphics.fillStyle="black"; 47 graphics.arc(centerX, centerY, blackBallSemi,0,Math.PI*2,true); 48 graphics.fill(); 49 graphics.beginPath(); 50 //以centerX,centerY为中心,绘制一个白色的瞳孔 51 //半径为blackBallSemi/2 52 graphics.fillStyle="white"; 53 graphics.arc(centerX,centerY, blackBallSemi/4,0,Math.PI*2,true); 54 graphics.fill(); 55 graphics.strokeStyle="red"; 56 for (var i = 0; i < angle; i++) { 57 graphics.moveTo(centerX-angle/2+i,centerY-30); 58 graphics.lineTo(centerX-angle/2+i, centerY-(Math.floor(Math.sin(Math.PI*i/angle)*ampl))); 59 graphics.moveTo(centerX-angle/2+i,centerY+30); 60 graphics.lineTo(centerX-angle/2+i,centerY+(Math.floor(Math.sin(Math.PI*i/angle)*ampl))); 61 graphics.stroke(); 62 } 63 64 65 } 66 // paint(); 67 setInterval(paint,30); 68 </script>