HTML5 Canvas眨眼睛动画
在网上发现一个java眨眼睛动画,把代码改成了HTML5 +JS,效果如下:
动画中有一些明显不足之处,请会的朋友指正,谢谢!
这里可以看效果:http://www.108js.com/article/article3/view/30157/eye.html
代码如下:
<html><body> <canvas width="300" height="300" id="canvas" style="background:black"></canvas></body></html><script>var canvas = document.getElementById('canvas'); var graphics = canvas.getContext('2d'); var centerX = canvas.width/2; var centerY = canvas.height/2; //设置角度值,同时也就眼睛的横坐标长度 var angle = 300; //因为眨眼采用的sin()函数组成,所以其自然有幅值这一个属性。 var amplitude = 30; //创建一个用于保存幅值的变化的变量,采用amplitude的缩写ampl,便于认识 ^_^ var ampl = 20; //灰眼球的半径 var blackBallSemi = 25; var flag = true; function paint() { if (flag) { ampl++; if (ampl >= amplitude) { flag = false; } }else { ampl--; if (ampl <= 0) { flag = true; } } //以centerX,centerY为中心,在眼睛所在的地方绘制一个白色的背景底色, //长度为angle,宽为amplitude*2 graphics.fillStyle="white"; graphics.fillRect(centerX-angle/2, centerY-amplitude, angle, amplitude*2); //以centerX,centerY为中心,绘制一个灰色的眼球 //半径为blackBallSemi*2 graphics.beginPath(); graphics.fillStyle="black"; graphics.arc(centerX, centerY, blackBallSemi,0,Math.PI*2,true); graphics.fill(); graphics.beginPath(); //以centerX,centerY为中心,绘制一个白色的瞳孔 //半径为blackBallSemi/2 graphics.fillStyle="white"; graphics.arc(centerX,centerY, blackBallSemi/4,0,Math.PI*2,true); graphics.fill(); graphics.strokeStyle="red"; for (var i = 0; i < angle; i++) { graphics.moveTo(centerX-angle/2+i,centerY-30); graphics.lineTo(centerX-angle/2+i, centerY-(Math.floor(Math.sin(Math.PI*i/angle)*ampl))); graphics.moveTo(centerX-angle/2+i,centerY+30); graphics.lineTo(centerX-angle/2+i,centerY+(Math.floor(Math.sin(Math.PI*i/angle)*ampl))); graphics.stroke(); } } // paint(); setInterval(paint,30);</script>