實現了鼠標跟隨物體轉動的效果: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 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!