js实现google网站的小眼睛

  • 发表于
  • 前端

没看之前,觉得会挺难的,今天看了别人的思路,于是自己摸索着也整了一个出来。感觉这东西也不太实用,不过把它挂在博客上什么的装饰一下还可以,但主要 是练习js,提高自己的编程能力啦~。写的时候,画张图,边分析边写,会容易些,另外就是一些初中数学知识的运用啦......

请先查看Demo

源码部分:

html:

Google eye!

css:

body {background-color: #888;}
#googleEye {
	background-color: #FFF;
	width: 324px;
	margin: 1em auto;
	padding-bottom: 1em;
	border: 1px solid #E1ECFE;
	text-align: center;
	vertical-align: middle;
}
#googleEye h1 {
	line-height: 30px;
	background-color: #E1ECFE;
	font-size: 16px;
	text-align: center;
	margin: 0 0 1em;
	padding: 0;
}
#googleEye div {
	display: inline-block;
	_display: inline;
	_zoom: 1;
	width: 117px;
	height: 117px;
	position: relative;
}
#leftEye {background: url(images/eye-r.gif) no-repeat center;}
#rightEye {background: url(images/eye-y.gif) no-repeat center;}
#googleEye div img {
	position: absolute;
	left: 51px;
	top: 51px;
	width: auto;
}

js:

function $(id) {
	return document.getElementById(id);
}

function addEvent(obj, type, handler) {
	if(obj.addEventListener) {
		obj.addEventListener(type, handler, false);
	} else if(obj.attachEvent) {
		obj.attachEvent('on' + type, handler);
	} else {
		obj['on' + type] = handler;
	}
}

(function() {
	addEvent(window, 'load', initAll);

	addEvent(document, "mousemove", function(event) {
		GEye.init(event.clientX, event.clientY);
	});

	function initAll() {
		var gEye1 = new GEye($('leftEye'));
		var gEye2 = new GEye($('rightEye'));
	}

	function GEye(eye) {
		this.eye = eye;
		this.pupil = eye.getElementsByTagName('img')[0];
		GEye.eyes.push(this);
	}
	GEye.eyes = [];
	GEye.eyeRadius = 58;//眼睛半径
	GEye.pupilRadius = 7;//瞳孔半径
	GEye.pupilRange = 41;//瞳孔活动范围
	GEye.getHypotenuse = function(h, v) {//已知直角三角形的两直角边,求斜边长
		return Math.sqrt(Math.pow(h, 2) + Math.pow(v, 2));
	}

	GEye.init = function(x, y) {
		for(var i=0; i<this.eyes.length; i++) {
			this.eyes[i].draw(x, y);
		};
	}

	GEye.prototype = {
		setPos: function(left, top) {
			this.pupil.style.left = left + 'px';
			this.pupil.style.top = top + 'px';
		},
		setAngle: function(sin, cos) {
			var left = GEye.eyeRadius - cos*GEye.pupilRange - GEye.pupilRadius;
			var top = GEye.eyeRadius - sin*GEye.pupilRange - GEye.pupilRadius;
			this.setPos(left, top);
		},
		getCenter: function() {//求眼睛圆心坐标
			return {
				X: this.eye.offsetLeft + GEye.eyeRadius,
				Y: this.eye.offsetTop + GEye.eyeRadius
			};
		},
		draw: function(mouseX, mouseY) {
			var center = this.getCenter();
			var len = GEye.getHypotenuse(center.X - mouseX, center.Y - mouseY);//鼠标顶点到眼睛圆心的距离
			if(len > GEye.pupilRange) {//在眼睛外
				var sin = (center.Y - mouseY)/len;
				var cos = (center.X - mouseX)/len;
				this.setAngle(sin, cos);
			} else {//在眼睛里面
				var left = mouseX - this.eye.offsetLeft - GEye.pupilRadius;
				var top = mouseY - this.eye.offsetTop - GEye.pupilRadius;
				this.setPos(left, top);
			};
		}
	}
})();