Vytvořte explodující logo pomocí CSS3 a MooTools nebo jQuery

Když mi přispěvatel MooTools a tvůrce moo4q Ryan Florence poprvé ukázal svůj vynikající příspěvek o animaci CSS, byl jsem zklamán. Jeho efekt explodujícího textu je úžasným příkladem síly CSS3 a špetky JavaScriptu. Chtěl jsem tento efekt implementovat na svůj nový redesign blogu, ale s trochu více popem, a tak jsem napsal nějaký kód MooTools, abych pořídil statický obrázek a udělal z něj animované, explodující mistrovské dílo. Dovolte mi, abych vám ukázal, jak jsem to udělal, a jako bonus jsem vytvořil úryvek jQuery, který dosahuje stejného efektu.

DemojQuery MooTools

Knihovna animací Ryana Florence

Ryanova knihovna animací CSS, která je k dispozici s vanilkovým JavaScriptem, MooTools nebo jQuery, a lze ji popsat pouze jako zkurvené umělecké dílo. Jeho knihovna animací je povolena pro mobilní zařízení, funguje v různých prohlížečích třídy A a je velmi kompaktní. Než budete pokračovat v tomto příspěvku, stáhněte si a prostudujte si Ryanovu knihovnu animací.

Ryanův příspěvek také obsahuje úžasné demo a několik užitečných funkcí. Některé z těchto funkcí zahrnují:

// reset transforms to this
var zeros = {x:0, y:0, z:0};

// Implement animation methods on the element prototype
Element.implement({
	
	// Scatter elements all over the place
	scatter: function(){
		return this.translate({
			x: Number.random(-1000, 1000),
			y: Number.random(-1000, 1000),
			z: Number.random(-500, 500)
		}).rotate({
			x: Number.random(-720, 720),
			y: Number.random(-720, 720),
			z: Number.random(-720, 720)
		});
	},
	
	// Return them to their original state
	unscatter: function(){ 
		return this.translate(zeros).rotate(zeros);
	},
	
	//  Frighten the image!  AHHHHHHHH!
	frighten: function(d){
		this.setTransition('timing-function', 'ease-out').scatter();
		setTimeout(function(){ 
			this.setTransition('timing-function', 'ease-in-out').unscatter();
		}.bind(this), 500);
		return this;
	},
	
	// Zoooooom into me
	zoom: function(delay){
		var self = this;
		this.scale(0.01);
		setTimeout(function(){
			self.setTransition({
				property: 'transform',
				duration: '250ms',
				'timing-function': 'ease-out'
			}).scale(1.2);
			setTimeout(function(){
				self.setTransition('duration', '100ms').scale(1);
			}, 250)
		}, delay);
	},
	
	// Create a slider
	makeSlider: function(){
		var open = false,
			next = this.getNext(),
			height = next.getScrollSize().y,
			transition = {
				property: 'height',
				duration: '500ms',
				transition: 'ease-out'
			};
		next.setTransition(transition);
		this.addEvent('click', function(){
			next.setStyle('height', open ? 0 : height);
			open = !open;
		});
	},
	
	// Scatter, come back
	fromChaos: (function(x){
		var delay = 0;
		return function(){
			var element = this;
			//element.scatter();
			setTimeout(function(){
				element.setTransition({
					property: 'transform',
					duration: '500ms',
					'timing-function': 'ease-out'
				});
				setTimeout(function(){
					element.unscatter();
					element.addEvents({
						mouseenter: element.frighten.bind(element),
						touchstart: element.frighten.bind(element)
					});
				}, delay += x);
			}, x);
		}
	}())

});

Nyní se vrhněme na explodující logo!

HTML

Rozložený prvek může být libovolného typu, ale pro účely tohoto příkladu použijeme prvek A s obrázkem na pozadí:

<a href="/" id="homeLogo">David Walsh Blog</a>

Ujistěte se, že prvek, který používáte, je blokový prvek nebo stylizovaný jako blok.

CSS

Původní prvek by měl být upraven podle velikosti (šířka a výška) s obrázkem na pozadí, který použijeme jako rozložený obrázek:

a#homeLogo	{ 
	width:300px; 
	height:233px; 
	text-indent:-3000px; 
	background:url(/wp-content/themes/2k11/images/homeLogo.png) 0 0 no-repeat; 
	display:block; 
	z-index:2; 
}
a#homeLogo span { 
	float:left;
	display:block;
	background-image:url(/wp-content/themes/2k11/images/homeLogo.png); 
	background-repeat:no-repeat;
}
.clear { clear:both; }

Nezapomeňte nastavit odsazení textu tak, aby se text odkazu nezobrazoval. Úlomky exploze budou prvky SPAN generované JavaScriptem, které se zobrazí jako v blokovém formátu. Všimněte si, že SPAN má stejný obrázek na pozadí jako prvek A – jednoduše upravíme pozici pozadí prvku tak, aby fungoval jako část loga, které každý SPAN představuje.

JavaScript MooTools

Prvním krokem je dát dohromady několik proměnných, které budeme potřebovat k výpočtu rozměrů prvků:

// Get the proper CSS prefix from the page
var cssPrefix = false;
switch(Browser.name) { // Implement only for Chrome, Firefox, and Safari
	case "safari":
	case "chrome":
		cssPrefix = "webkit";
		break;
	case "firefox":
		cssPrefix = "moz";
		break;
}

if(cssPrefix) {
	
	// 300 x 233
	var cols = 10; // Desired columns
	var rows = 8; // Desired rows
	var totalWidth = 300; // Logo width
	var totalHeight = 233; // Logo height
	var singleWidth = Math.ceil(totalWidth / cols); // Shard width
	var singleHeight = Math.ceil(totalHeight / rows); // Shard height
	var shards = []; // Array of SPANs
	

Všimněte si, že jsem výslovně nastavil požadovaný počet sloupců a řádků. Nechcete, aby byly střepy příliš velké nebo příliš malé, takže neváhejte experimentovat. K získání čísel sloupců a řádků byste pravděpodobně mohli použít jiný výpočet, ale to nechám na vás.

Dalším krokem je procházení každého řádku a sloupce a vytvoření nového prvku SPAN pro každý fragment. Pozice pozadí, šířka a výška ROZSAHU budou vypočteny pomocí ... výpočtů ... jsme ... vypočítali ... výše.

// Remove the text and background image from the logo
var logo = document.id("homeLogo").set("html","").setStyles({ backgroundImage: "none" });

// For every desired row
rows.times(function(rowIndex) {
	// For every desired column
	cols.times(function(colIndex) {
		// Create a SPAN element with the proper CSS settings
		// Width, height, browser-specific CSS
		var element = new Element("span",{
			style: "width:" + (singleWidth) + "px;height:" + (singleHeight) + "px;background-position:-" + (singleHeight * colIndex) + "px -" + (singleWidth * rowIndex) + "px;-" + cssPrefix + "-transition-property: -" + cssPrefix + "-transform; -" + cssPrefix + "-transition-duration: 200ms; -" + cssPrefix + "-transition-timing-function: ease-out; -" + cssPrefix + "-transform: translateX(0%) translateY(0%) translateZ(0px) rotateX(0deg) rotateY(0deg) rotate(0deg);"
		}).inject(logo);
		// Save it
		shards.push(element);
	});
	// Create a DIV clear for next row
	new Element("div",{ clear: "clear" }).inject(logo);
});

U prvků SPAN si všimnete, že je na něj nastaveno několik vlastností CSS3, což prohlížeči umožňuje provádět svá kouzla. Použití CSS3 je mnohem méně náročné na zdroje v prohlížeči než použití JavaScriptu k provedení všech animací.

Posledním krokem je volání metody fromChaos, kterou poskytuje CSS animační kód Ryana Florence, aby se to šílenství dalo do pohybu!

// Chaos!
$$(shards).fromChaos(1000);

Tady to máš! Zcela automatizovaná metoda rozkládání obrázku pomocí CSS3 a MooTools JavaScript!

JavaScript jQuery

Ryan také napsal kód animace CSS v jQuery, takže můžete snadno vytvořit srovnatelný efekt s jQuery!

Number.random = function(min, max){
	return Math.floor(Math.random() * (max - min + 1) + min);
};

var zeros = {x:0, y:0, z:0};

jQuery.extend(jQuery.fn, {

	scatter: function(){
		return this.translate({
			x: Number.random(-1000, 1000),
			y: Number.random(-1000, 1000),
			z: Number.random(-500, 500)
		}).rotate({
			x: Number.random(-720, 720),
			y: Number.random(-720, 720),
			z: Number.random(-720, 720)
		});
	},

	unscatter: function(){ 
		return this.translate(zeros).rotate(zeros);
	},

	frighten: function(d){
		var self = this;
		this.setTransition('timing-function', 'ease-out').scatter();
		setTimeout(function(){
			self.setTransition('timing-function', 'ease-in-out').unscatter();
		}, 500);
		return this;
	},

	zoom: function(delay){
		var self = this;
		this.scale(0.01);
		setTimeout(function(){
			self.setTransition({
				property: 'transform',
				duration: '250ms',
				'timing-function': 'ease-out'
			}).scale(1.2);
			setTimeout(function(){
				self.setTransition('duration', '100ms').scale(1);
			}, 250)
		}, delay);
		return this;
	},

	makeSlider: function(){
		return this.each(function(){
			var $this = $(this),
				open = false,
				next = $this.next(),
				height = next.attr('scrollHeight'),
				transition = {
					property: 'height',
					duration: '500ms',
					transition: 'ease-out'
				};
			next.setTransition(transition);
			$this.bind('click', function(){
				next.css('height', open ? 0 : height);
				open = !open;
			});
		})
	},

	fromChaos: (function(){
		var delay = 0;
		return function(){
			return this.each(function(){
				var element = $(this);
				//element.scatter();
				setTimeout(function(){
					element.setTransition({
						property: 'transform',
						duration: '500ms',
						'timing-function': 'ease-out'
					});
					setTimeout(function(){
						element.unscatter();
						element.bind({
							mouseenter: jQuery.proxy(element.frighten, element),
							touchstart: jQuery.proxy(element.frighten, element)
						});
					}, delay += 100);
				}, 1000);
			})
		}
	}())

});


// When the DOM is ready...
$(document).ready(function() {
	
	// Get the proper CSS prefix
	var cssPrefix = false;
	if(jQuery.browser.webkit) {
		cssPrefix = "webkit";
	}
	else if(jQuery.browser.mozilla) {
		cssPrefix = "moz";
	}
	
	// If we support this browser
	if(cssPrefix) {
		// 300 x 233
		var cols = 10; // Desired columns
		var rows = 8; // Desired rows
		var totalWidth = 300; // Logo width
		var totalHeight = 233; // Logo height
		var singleWidth = Math.ceil(totalWidth / cols); // Shard width
		var singleHeight = Math.ceil(totalHeight / rows); // Shard height
		
		// Remove the text and background image from the logo
		var logo = jQuery("#homeLogo").css("backgroundImage","none").html("");
		
		// For every desired row
		for(x = 0; x < rows; x++) {
			var last;
			//For every desired column
			for(y = 0; y < cols; y++) {
				// Create a SPAN element with the proper CSS settings
				// Width, height, browser-specific CSS
				last = jQuery("<span />").attr("style","width:" + (singleWidth) + "px;height:" + (singleHeight) + "px;background-position:-" + (singleHeight * y) + "px -" + (singleWidth * x) + "px;-" + cssPrefix + "-transition-property: -" + cssPrefix + "-transform; -" + cssPrefix + "-transition-duration: 200ms; -" + cssPrefix + "-transition-timing-function: ease-out; -" + cssPrefix + "-transform: translateX(0%) translateY(0%) translateZ(0px) rotateX(0deg) rotateY(0deg) rotate(0deg);");
				// Insert into DOM
				logo.append(last);
			}
			// Create a DIV clear for row
			last.append(jQuery("<div />").addClass("clear"));
		}
		
		// Chaos!
		jQuery("#homeLogo span").fromChaos();
	}
});

Ne tak krásný jako kód MooTools, samozřejmě, ale stále efektivní!

DemojQuery MooTools

A tady to máte:CSS animace, JavaScript a dynamické efekty. Moje oblíbená část tohoto efektu je, jak málo kódu je zapojeno. S tímhle dostanete hodně peněz. Samozřejmě, použití tohoto efektu všude by jistě vyvolalo sténání, takže jej používejte moudře!