实现了鼠标跟随物体转动的效果:MouseFollower.js
jopen
11年前
MouseFollower.js 实现了鼠标跟随的物体转动效果,类似 Linux 下的大眼睛。
MouseFollower = (function(){ var store = [], //contains an object with an element & invert property xdeg = ydeg = 0, //the current rotationAngles of the cube that is currently being handled sPos = {}, //relative pos on screen, seen from the document invert = 1; //look to the mouse cursor or away from it document.body.onmousemove = followElements; /* helper functions*/ function prefixStyle(el,p,style){ var prefixes = ["webkit","moz","o",""], i = 0; p = p.charAt(0).toUpperCase() + p.slice(1); [].forEach.call(prefixes, function(prefix){ if( prefix == ""){ p = p.charAt(0).toLowerCase() + p.slice(1); el.style[prefix + p] = style; }else{ el.style[prefix + p] = style; } }); } function posOnScreen(el){ return el.getBoundingClientRect(); } /* iterate over the store, get each element and apply the right rotation angles. Invert the view angle if set. */ function followElements( e ){ [].forEach.call( store , function(item, index){ sPos = posOnScreen( item.element ); /* if the element is in the viewport */ if( sPos.top > -sPos.height || sPos.top < document.documentElement.clientHeight + sPos.height){ invert = item.invert ? -1 : 1; xdeg = -90 * invert * ( e.clientX - sPos.left ) / document.documentElement.clientWidth + "deg"; ydeg = 90 * invert * ( e.clientY - sPos.top ) / document.documentElement.clientHeight + "deg"; prefixStyle(item.element,"transform","rotateY("+xdeg+") rotateX("+ydeg+")"); }else{ } }); } /* public methods */ /* add an element to the store. usage: MouseFollower.add({ element: document.querySelector(".cube"), invert: true }); */ function add( opt ){ if( opt && opt.element ){ store.push( opt ); } } //TODO function remove(arguments) { } function stop() { store = []; } return { add: add, remove: remove, stop: stop } })();