JavaScript: GIFless animation. JavaScript: GIFless анімації. Animate images,logos with jQuery Анімація зображення, логотипи з JQuery
Posted on 23. Опублікований 23. Jul, 2009 by Dragos in Coding , Design , JavaScript & Ajax Липень, 2009 Dragos в кодування, дизайн, JavaScript & Ajax
After playing some time with position relative and absolute, I've noticed one a great aspect of the png image format (probably gif images are also good, but since we are trying to create a GIFless animation, I won't use any gif images in this tutorial). Після грав деякий час з позиції відносної і абсолютної, я помітив одну велику аспектом формат зображень PNG (ймовірно, малюнок зображення також є хорошими, але так як ми намагаємося створити GIFless анімація, я не буду використовувати будь-який малюнок зображення У цьому уроці).
So here's aa PNG (transparent text), with the name of this website: Так от А. PNG (прозорий текст), з ім'ям цього сайту:
The trick of animating images, without the need of using the GIF image format features, are as follow: Трюк анімації зображення, без необхідності використання GIF особливостей формату зображення, є наступні:
We have an image with transparent text written on it. У нас є зображення з прозорим текст, написаний на ній. To animate the transparent text, we need to place a background image below the actual image and move this background image, in order to create a so called “animation”. Для анімації прозорими тексту, ми повинні поставити фонову картинку нижче фактичної іміджу і просування цього фонового малюнка, з тим щоб створити так званий "Анімація". To be more precise, the image we want to be animated should have a higher z-index than the background image below it (it's like working with layers in Photoshop). Щоб бути більш точним, то зображення ми хочемо бути анімованими повинні мати вищу Z-індексу, ніж фонові зображення нижче його (це подобається працювати з шарами в Photoshop). In order to animate the background image we need some javascript work to be done. Для анімації фонового зображення нам знадобляться деякі JavaScript роботу належить зробити. Of course, as a big fan of jQuery, I've used jQuery to do all the animation stuff. Зрозуміло, як великий шанувальник JQuery, я використав Jquery зробити все анімації матеріали.
Here's the script I've come up with: Ось сценарій я придумав:
(function($){ $.fn.enliven = function(options) { var defaults = { bgImage: '', duration:3000 }; var options = $.extend(defaults, options); var imH=this.attr("height"), imW=this.attr("width"); this.wrap(' '); this.css("position","absolute"); $('#'+this.attr("className")+'Cont').append(' '); var maxLeft=($('.lbg'+this.attr("className")).attr('clientWidth')-this.attr('width'))/2, maxTop=($('.lbg'+this.attr("className")).attr('clientHeight')-this.attr('height'))/2; function getrand() { var nr=Math.floor(Math.random()*2); return nr==0?-1:1; } function randimate(obj) { var ph=Math.floor(imH*20/100),pw=Math.floor(imW*20/100); newLeft=$(".lbg"+obj.attr("className")).attr("offsetLeft")+Math.floor(Math.random()*pw)*getrand(); newTop=$(".lbg"+obj.attr("className")).attr("offsetTop")+Math.floor(Math.random()*ph)*getrand(); if(newLeft>0) newLeft=0; else if(newLeft<-maxLeft) newLeft=-maxLeft+1; if(newTop>0) newTop=0; else if(newTop<-maxTop) newTop=-maxTop+1; $('.lbg'+obj.attr("className")).animate({left:newLeft+"px",top:newTop+"px"},defaults.duration,"linear",function(){ randimate(obj); }); } return this.each(function(){ randimate($(this)); }); }; })(jQuery); (функція ($) ($. fn.enliven = функція (варіанти) (VAR промовчанням = (bgImage:'', тривалість: 3000); VAR параметри = $. продовжити (за замовчуванням, опціони); VAR ПМХ this.attr = ( "Висота"), IMW = this.attr ( "ширина"); this.wrap (''); this.css ( "Позиція", "абсолютний"); $('#'+ this.attr ( "ClassName" ) + 'Продовження'). Append (''); VAR maxLeft =($('. LBG '+ this.attr ( "ClassName")). Attr (' ClientWidth ')-this.attr (' ширина ')) / 2, maxTop =($('. LBG '+ this.attr ( "ClassName")). Attr (' ClientHeight ')-this.attr (' Висота ')) / 2; функція getrand () (VAR NR = Math.floor (Math.random () * 2); повернення Nr == 0? -1:1;) функція randimate (ЦП) (VAR рН = Math.floor (ПМХ * 20/100), PW = Math.floor (МКМ * 20/100); newLeft =$(". LBG "+ obj.attr (" ClassName ")). Attr (" offsetLeft ") + Math.floor (Math.random () * PW) * getrand () ; newTop =$(". LBG "+ obj.attr (" ClassName ")). Attr (" offsetTop ") + Math.floor (Math.random () * PH) * getrand (); якщо (newLeft> 0) newLeft = 0; Else If (newLeft <-maxLeft) newLeft =- maxLeft 1, якщо (newTop> 0) newTop = 0; Else If (newTop <-maxTop) newTop =- maxTop 1; $ ( '. LBG' + obj.attr ( "ClassName")). Animate ((ліворуч: newLeft + "ПВ", вгорі: newTop + "PX"), defaults.duration, "лінійні", функція () (randimate (ЦП );));) повернення this.each (функція () (randimate ($ (це ));));))) (JQuery); The code above works as a plugin of jQuery, so it should be included in the page, after the inclusion of jQuery. Цей код працює як плагін JQuery, тому він повинен бути включений в сторінку, після включення Jquery. In order to animate an image, you should use this code: Щоб оживити зображення, ви повинні використовувати цей код:
$('image_selector').enliven({bgImage:"./path_to_background_image.png",duration:1000}); //duration is the time of one time background animation $ ( 'Image_selector'). Оживити ((bgImage: ". / Path_to_background_image.png", тривалість: 1000)); / / тривалість час однієї анімації фону час Here's a crazy example 1: http://iwebdevel.com/wp-content/uploads/2009/07/logo.php Ось Crazy Приклад 1: http://iwebdevel.com/wp-content/uploads/2009/07/logo.php
Here's another non-crazy example 2: http://iwebdevel.com/wp-content/uploads/2009/07/logo2.php Ось ще один не-Crazy Приклад 2: http://iwebdevel.com/wp-content/uploads/2009/07/logo2.php
If you like the idea and want more features, drop me a line in a comment and I'll try to improve the code and add more features Якщо вам подобається ідея і ви хочете більше функцій, черкніте мені в коментарі, і я постараюся, щоб поліпшити код і додати нові функції ![]()
Related posts: Схожі повідомлення:
- JavaScript: What if jQuery animation doesn't fire/start? JavaScript: Що робити, якщо Jquery анімація не спрацьовує / почати?
- JavaScript: How to get the index (position within a group) of an object with jQuery? JavaScript: Як отримати індекс (позиція в групі) об'єкта з JQuery?
- Javascript: How to validate email address with JavaScript? JavaScript: Як перевірити адресу електронної пошти з JavaScript?
- JavaScript: Get anchor from URL JavaScript: Отримати якір, з URL
- JavaScript: Send function as a parameter to another function (callbacks) JavaScript: Надіслати функцію як параметр в іншу функцію (функції зворотного виклику)













































