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 от Драгош в кодиране, дизайн, JavaScript & Аякс
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 формат на изображението (вероятно Gif изображения са добри, но тъй като ние се опитваме да създадем GIFless анимация, аз няма да използвате Gif изображения В този урок).
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) { $. fn.enliven = функция (опции) ( var defaults = { VAR подразбиране = ( bgImage: '', bgImage:'', duration:3000 Продължителност: 3000 }; ); var options = $.extend(defaults, options); VAR варианти = $. разшири (по подразбиране, опции); var imH=this.attr("height"), VAR imH = this.attr ( "височина"), imW=this.attr("width"); imW = this.attr ( "широчина"); this.wrap(' this.wrap ( ' '); '); this.css("position","absolute"); this.css ( "положение", "абсолютна"); $('#'+this.attr("className")+'Cont').append(' $('#'+ this.attr ( "className") + "Конт"). добавяне ( " '); '); var VAR maxLeft=($('.lbg'+this.attr("className")).attr('clientWidth')-this.attr('width'))/2, maxLeft =($('. LBG "+ this.attr (" className ")). attr ( 'clientWidth")-this.attr ( "широчина")) / 2, maxTop=($('.lbg'+this.attr("className")).attr('clientHeight')-this.attr('height'))/2; maxTop =($('. LBG "+ this.attr (" className ")). attr ( 'clientHeight")-this.attr ( "височина")) / 2; function getrand() { getrand функция () ( var nr=Math.floor(Math.random()*2); VAR НД = Math.floor (Math.random () * 2); return nr==0?-1:1; връщане Nr == 0? -1:1; } ) function randimate(obj) { функция randimate (OBJ) ( var ph=Math.floor(imH*20/100),pw=Math.floor(imW*20/100); VAR рН = Math.floor (imH * 20/100), PW = Math.floor (imW * 20/100); newLeft=$(".lbg"+obj.attr("className")).attr("offsetLeft")+Math.floor(Math.random()*pw)*getrand(); 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(); newTop =$(". LBG "+ obj.attr (" className ")). attr (" offsetTop ") + Math.floor (Math.random () * рН) * getrand (); if(newLeft>0) newLeft=0; IF (newLeft> 0) newLeft = 0; else if(newLeft<-maxLeft) newLeft=-maxLeft+1; if(newTop>0) newTop=0; иначе, ако (newLeft <-maxLeft) newLeft =- maxLeft 1; ако (newTop> 0) newTop = 0; else if(newTop<-maxTop) иначе, ако (newTop <-maxTop) newTop=-maxTop+1; newTop =- maxTop 1; $('.lbg'+obj.attr("className")).animate({left:newLeft+"px",top:newTop+"px"},defaults.duration,"linear",function(){ randimate(obj); }); $ ( '. LBG "+ obj.attr (" className ")). анимирате ((ляво: newLeft +" пиксела ", Горе: newTop +" пиксела "), defaults.duration," линейно ", функция () (randimate (OBJ );)); } ) return this.each(function(){ връщане this.each (функция () ( randimate($(this)); randimate ($ (тази)); }); )); }; ); })(jQuery); )) (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 Ето един луд пример 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 Ето друг не-луд пример 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: Get anchor from URL JavaScript: Вземи котва от URL
- Javascript: How to validate email address with JavaScript? Javascript: Как да се валидира имейл адрес с JavaScript?
- JavaScript: Send function as a parameter to another function (callbacks) JavaScript: Изпрати функция като параметър на друга функция (Callbacks)













































