简明现代魔法 -> web设计理念 -> 让眼睛始终注视着你的鼠标

让眼睛始终注视着你的鼠标

2011-03-10

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

效果演示:

Google eye!

JavaScript Code

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);
			};
		}
	}
})();
随机文章推荐
网站分类


注:如需转载本文,请注明出处(原文链接),谢谢。更多精彩内容,请进入简明现代魔法首页。

进入新博客
喜欢本文,就分享它吧
给我留言
您的名字:
您的邮件:
您的网站:


 

copyright © 2009 简明现代魔法    学习、分享、进步

power by Gonn 感谢所有关心和支持本站的朋友们