您的位置:首页 - HTML5
javascript+Canvas眨眼睛动画

效果如下:



代码如下:

<html>
<body>
<canvas width="300" height="300" id="keleyieye" style="background:black"></canvas>
</body>
</html>
<script>

var keleyieye = document.getElementById('keleyieye');
var graphics = keleyieye.getContext('2d');
var centerX = keleyieye.width/2;
var centerY = keleyieye.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>
本站导航
相关文章
柯乐义 Copyright© keleyi.com