javascript
JS JQuery实现简单的鼠标移动动画效果
JS JQuery實現(xiàn)簡單的鼠標(biāo)移動動畫效果
說明:
之前看到過很多別人寫的的網(wǎng)頁鼠標(biāo)特效,感覺很炫酷。
但是那些都涉及到復(fù)雜的數(shù)學(xué)知識和邏輯,我沒有能力寫出類似的鼠標(biāo)效果,于是我仿照一般的顯示鼠標(biāo)移動軌跡特效,使用js和dom元素寫出了一個簡單的鼠標(biāo)移動效果。
其中涉及到的知識并不復(fù)雜,只需要熟悉js和jquery即可。
運行效果:
思路:
主要是給document對象添加mousemove鼠標(biāo)移動事件,創(chuàng)建并操控記錄鼠標(biāo)位置的div。
程序中用到了旋轉(zhuǎn)效果,因此除jquery外還需要引入jQueryRotate這個jquery旋轉(zhuǎn)動畫庫。
該程序不需要依賴css樣式,故除jquery和jQueryRotateCompressedz庫外,只需要引入一個js文件即可在網(wǎng)頁中使用該效果。
需要注意的是,雖然這個程序只是一個邏輯簡單的鼠標(biāo)移動效果,但在鼠標(biāo)移動時依然會消耗較多的電腦性能。因為在鼠標(biāo)移動時瀏覽器會同時處理三個定時器和一個鼠標(biāo)移動事件,在幾乎每個步驟中還會對dom元素數(shù)組中的每一個元素都進行操作。
這顯然是需要進行優(yōu)化的,但我目前還沒有學(xué)會能夠進一步優(yōu)化的方法。
代碼:
jQueryRotateCompressed jQuery旋轉(zhuǎn)動畫庫壓縮代碼
// VERSION: 2.3 LAST UPDATE: 11.07.2013 /** Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php** Made by Wilq32, wilq32@gmail.com, Wroclaw, Poland, 01.2009* Website: http://jqueryrotate.com*/ (function(k){for(var d,f,l=document.getElementsByTagName("head")[0].style,h=["transformProperty","WebkitTransform","OTransform","msTransform","MozTransform"],g=0;g<h.length;g++)void 0!==l[h[g]]&&(d=h[g]);d&&(f=d.replace(/[tT]ransform/,"TransformOrigin"),"T"==f[0]&&(f[0]="t"));eval('IE = "v"=="\v"');jQuery.fn.extend({rotate:function(a){if(0!==this.length&&"undefined"!=typeof a){"number"==typeof a&&(a={angle:a});for(var b=[],c=0,d=this.length;c<d;c++){var e=this.get(c);if(e.Wilq32&&e.Wilq32.PhotoEffect)e.Wilq32.PhotoEffect._handleRotation(a); else{var f=k.extend(!0,{},a),e=(new Wilq32.PhotoEffect(e,f))._rootObj;b.push(k(e))}}return b}},getRotateAngle:function(){for(var a=[0],b=0,c=this.length;b<c;b++){var d=this.get(b);d.Wilq32&&d.Wilq32.PhotoEffect&&(a[b]=d.Wilq32.PhotoEffect._angle)}return a},stopRotate:function(){for(var a=0,b=this.length;a<b;a++){var c=this.get(a);c.Wilq32&&c.Wilq32.PhotoEffect&&clearTimeout(c.Wilq32.PhotoEffect._timer)}}});Wilq32=window.Wilq32||{};Wilq32.PhotoEffect=function(){return d?function(a,b){a.Wilq32={PhotoEffect:this}; this._img=this._rootObj=this._eventObj=a;this._handleRotation(b)}:function(a,b){this._img=a;this._onLoadDelegate=[b];this._rootObj=document.createElement("span");this._rootObj.style.display="inline-block";this._rootObj.Wilq32={PhotoEffect:this};a.parentNode.insertBefore(this._rootObj,a);if(a.complete)this._Loader();else{var c=this;jQuery(this._img).bind("load",function(){c._Loader()})}}}();Wilq32.PhotoEffect.prototype={_setupParameters:function(a){this._parameters=this._parameters||{};"number"!== typeof this._angle&&(this._angle=0);"number"===typeof a.angle&&(this._angle=a.angle);this._parameters.animateTo="number"===typeof a.animateTo?a.animateTo:this._angle;this._parameters.step=a.step||this._parameters.step||null;this._parameters.easing=a.easing||this._parameters.easing||this._defaultEasing;this._parameters.duration=a.duration||this._parameters.duration||1E3;this._parameters.callback=a.callback||this._parameters.callback||this._emptyFunction;this._parameters.center=a.center||this._parameters.center|| ["50%","50%"];this._rotationCenterX="string"==typeof this._parameters.center[0]?parseInt(this._parameters.center[0],10)/100*this._imgWidth*this._aspectW:this._parameters.center[0];this._rotationCenterY="string"==typeof this._parameters.center[1]?parseInt(this._parameters.center[1],10)/100*this._imgHeight*this._aspectH:this._parameters.center[1];a.bind&&a.bind!=this._parameters.bind&&this._BindEvents(a.bind)},_emptyFunction:function(){},_defaultEasing:function(a,b,c,d,e){return-d*((b=b/e-1)*b*b*b- 1)+c},_handleRotation:function(a,b){d||this._img.complete||b?(this._setupParameters(a),this._angle==this._parameters.animateTo?this._rotate(this._angle):this._animateStart()):this._onLoadDelegate.push(a)},_BindEvents:function(a){if(a&&this._eventObj){if(this._parameters.bind){var b=this._parameters.bind,c;for(c in b)b.hasOwnProperty(c)&&jQuery(this._eventObj).unbind(c,b[c])}this._parameters.bind=a;for(c in a)a.hasOwnProperty(c)&&jQuery(this._eventObj).bind(c,a[c])}},_Loader:function(){return IE?function(){var a= this._img.width,b=this._img.height;this._imgWidth=a;this._imgHeight=b;this._img.parentNode.removeChild(this._img);this._vimage=this.createVMLNode("image");this._vimage.src=this._img.src;this._vimage.style.height=b+"px";this._vimage.style.width=a+"px";this._vimage.style.position="absolute";this._vimage.style.top="0px";this._vimage.style.left="0px";this._aspectW=this._aspectH=1;this._container=this.createVMLNode("group");this._container.style.width=a;this._container.style.height=b;this._container.style.position= "absolute";this._container.style.top="0px";this._container.style.left="0px";this._container.setAttribute("coordsize",a-1+","+(b-1));this._container.appendChild(this._vimage);this._rootObj.appendChild(this._container);this._rootObj.style.position="relative";this._rootObj.style.width=a+"px";this._rootObj.style.height=b+"px";this._rootObj.setAttribute("id",this._img.getAttribute("id"));this._rootObj.className=this._img.className;for(this._eventObj=this._rootObj;a=this._onLoadDelegate.shift();)this._handleRotation(a, !0)}:function(){this._rootObj.setAttribute("id",this._img.getAttribute("id"));this._rootObj.className=this._img.className;this._imgWidth=this._img.naturalWidth;this._imgHeight=this._img.naturalHeight;var a=Math.sqrt(this._imgHeight*this._imgHeight+this._imgWidth*this._imgWidth);this._width=3*a;this._height=3*a;this._aspectW=this._img.offsetWidth/this._img.naturalWidth;this._aspectH=this._img.offsetHeight/this._img.naturalHeight;this._img.parentNode.removeChild(this._img);this._canvas=document.createElement("canvas"); this._canvas.setAttribute("width",this._width);this._canvas.style.position="relative";this._canvas.style.left=-this._img.height*this._aspectW+"px";this._canvas.style.top=-this._img.width*this._aspectH+"px";this._canvas.Wilq32=this._rootObj.Wilq32;this._rootObj.appendChild(this._canvas);this._rootObj.style.width=this._img.width*this._aspectW+"px";this._rootObj.style.height=this._img.height*this._aspectH+"px";this._eventObj=this._canvas;for(this._cnv=this._canvas.getContext("2d");a=this._onLoadDelegate.shift();)this._handleRotation(a, !0)}}(),_animateStart:function(){this._timer&&clearTimeout(this._timer);this._animateStartTime=+new Date;this._animateStartAngle=this._angle;this._animate()},_animate:function(){var a=+new Date,b=a-this._animateStartTime>this._parameters.duration;if(b&&!this._parameters.animatedGif)clearTimeout(this._timer);else{if(this._canvas||this._vimage||this._img)a=this._parameters.easing(0,a-this._animateStartTime,this._animateStartAngle,this._parameters.animateTo-this._animateStartAngle,this._parameters.duration), this._rotate(~~(10*a)/10);this._parameters.step&&this._parameters.step(this._angle);var c=this;this._timer=setTimeout(function(){c._animate.call(c)},10)}this._parameters.callback&&b&&(this._angle=this._parameters.animateTo,this._rotate(this._angle),this._parameters.callback.call(this._rootObj))},_rotate:function(){var a=Math.PI/180;return IE?function(a){this._angle=a;this._container.style.rotation=a%360+"deg";this._vimage.style.top=-(this._rotationCenterY-this._imgHeight/2)+"px";this._vimage.style.left= -(this._rotationCenterX-this._imgWidth/2)+"px";this._container.style.top=this._rotationCenterY-this._imgHeight/2+"px";this._container.style.left=this._rotationCenterX-this._imgWidth/2+"px"}:d?function(a){this._angle=a;this._img.style[d]="rotate("+a%360+"deg)";this._img.style[f]=this._parameters.center.join(" ")}:function(b){this._angle=b;b=b%360*a;this._canvas.width=this._width;this._canvas.height=this._height;this._cnv.translate(this._imgWidth*this._aspectW,this._imgHeight*this._aspectH);this._cnv.translate(this._rotationCenterX, this._rotationCenterY);this._cnv.rotate(b);this._cnv.translate(-this._rotationCenterX,-this._rotationCenterY);this._cnv.scale(this._aspectW,this._aspectH);this._cnv.drawImage(this._img,0,0)}}()};IE&&(Wilq32.PhotoEffect.prototype.createVMLNode=function(){document.createStyleSheet().addRule(".rvml","behavior:url(#default#VML)");try{return!document.namespaces.rvml&&document.namespaces.add("rvml","urn:schemas-microsoft-com:vml"),function(a){return document.createElement("<rvml:"+a+' class="rvml">')}}catch(a){return function(a){return document.createElement("<"+ a+' xmlns="urn:schemas-microsoft.com:vml" class="rvml">')}}}())})(jQuery);鼠標(biāo)移動動畫代碼:
// 需要配合jquery庫和jquery rotate compressed庫使用 $(() => {// 鼠標(biāo)元素和樣式const moveObj = $(`<div></div>`);moveObj.css({width: '40px', height: '40px', background: 'yellow',position: 'absolute',top: '0', left: '0'});const $body = $('body'); // jquery body對象$body.append(moveObj); // 向body中追加鼠標(biāo)樣式元素$body.css('cursor', 'none'); // 隱藏bodyconst $doc = $(document); // jquery document對象const moveElements = [], elemAssocArray = []; // 移動效果元素數(shù)組, 移動效果元素關(guān)聯(lián)數(shù)組const elementsLength = 28; // 移動效果元素數(shù)組長度const defDeg = -45; // 效果元素默認(rèn)旋轉(zhuǎn)角度const timeMs = 46; // 效果元素在屏幕上留存的時間,單位ms// 初始化效果元素數(shù)組for (let i = 0; i < elementsLength; i++) {const $element = $('<div></div>');$element.css({width: '30px', height: '30px', // background: 'blue', display: 'none', position: 'absolute',transform: `rotate(${defDeg}deg)`});moveElements[i] = $element;elemAssocArray[i] = {rotateDeg: defDeg, time: timeMs};$body.append($element);}// 顏色數(shù)組const colorArray = ['yellow', 'blue', 'red', 'green', 'aquamarine', 'darkblue', 'deepskyblue', 'coral'];const colorArrayLen = colorArray.length;const toFree = (n, m) => parseInt(Math.random() * (m - n) + n); // 生成隨機數(shù)// document鼠標(biāo)移動事件let count = 0;let flag = false;$doc.mousemove(e => {// 鼠標(biāo)樣式位置moveObj.css({left: e.pageX - moveObj.width() / 2, top: e.pageY - moveObj.height() / 2});// 移動效果const $moveElement = moveElements[count];if(flag && $moveElement) {$moveElement.css({display: 'block', left: e.pageX - $moveElement.width() / 2, top: e.pageY - $moveElement.height() / 2 ,background: colorArray[toFree(0, colorArrayLen)],// background: 'blue'});$moveElement.rotate({duration: 2000, animateTo: defDeg});elemAssocArray[count].rotateDeg = defDeg;elemAssocArray[count].time = timeMs;count++;if (count >= elementsLength)count = 0;flag = false;}});// 元素顯示間隔定時器setInterval(() => flag = true, 13);// 消除元素定時器 setInterval(() => {elemAssocArray.forEach((item, index) => (item.time < 0) ? moveElements[index].fadeOut(40) : item.time--);}, 1);// 移動元素旋轉(zhuǎn)動畫定時器const rotateTime = 1220; // 旋轉(zhuǎn)時間setInterval(() => {moveElements.forEach((item, index) => {if (item.css('display') === 'none') return;elemAssocArray[index].rotateDeg -= 360;item.rotate({duration: rotateTime, animateTo: defDeg + elemAssocArray[index].rotateDeg});});}, rotateTime); });歡迎提出意見和建議,感謝支持。
總結(jié)
以上是生活随笔為你收集整理的JS JQuery实现简单的鼠标移动动画效果的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第一次带美瞳,突然发现眼睛大了10倍!
- 下一篇: JavaScript大师必须掌握的12个