效果如下:
代碼如下:
<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>