实现了鼠标跟随物体转动的效果:MouseFollower.js
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 } })();
本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!