1. 程式人生 > >重力感應看大圖效果

重力感應看大圖效果

var PhotoTilt = function(option) {

	'use strict';

	var imgUrl = option.url,
		container = option.container,
		latestTilt = 0,
		viewport,
		timeoutID,
		imgData,
		img,
		imgLoader,
		centerOffset = 0,
		tiltCenterOffset = 0;

	window.requestAnimationFrame =  window.requestAnimationFrame ||
								window.webkitRequestAnimationFrame;

	var init = function() {
		generateViewPort();
		preloadImg(imgUrl, function() {
			img = imgLoader.cloneNode(false);
			generateImgData();
			imgLoader = null;
			render();
			addEventListeners();
		});
	};

	var updatePosition = function() {
		var tilt = latestTilt,
			pxToMove;

		if (tilt > 0) {
			tilt = -Math.min(tilt, 20);
		} else {
			tilt = -Math.max(tilt, 20 * -1);
		}
		pxToMove = (tilt * centerOffset) / 20;
		updateImgPosition( (centerOffset + pxToMove) * -1);
		window.requestAnimationFrame(updatePosition);
	};

	var updateImgPosition = function(pxToMove) {
		img.style.webkitTransform = "translateX(" + Math.round(pxToMove) + "px)";
	};

	var addEventListeners = function() {
		if (window.DeviceOrientationEvent) {
			var averageGamma = [];
			window.addEventListener('deviceorientation', function(eventData) {
				if (averageGamma.length > 8) {
					averageGamma.shift();
				}
				averageGamma.push(eventData.gamma);
				latestTilt = averageGamma.reduce(function(a, b) { return a+b; }) / averageGamma.length;
			}, false);
			window.requestAnimationFrame(updatePosition);
		}

		window.addEventListener('resize', function() {
			window.clearTimeout(timeoutID);
			timeoutID = window.setTimeout(function() {
				generateViewPort();
				container.innerHTML = "";
				render();
			}, 100);
		}, false);
	};

	var generateViewPort = function() {
		viewport = {
			width: parseInt(document.body.clientWidth, 10),
			height: parseInt(document.body.clientHeight, 10)
		};
	};
	var render = function() {
		img.height = viewport.height;
		var resizedImgWidth = (imgData.aspectRatio * img.height);
		var delta = resizedImgWidth - viewport.width;
		centerOffset = delta / 2;
		updatePosition();
		container.appendChild(img);
	};

	var generateImgData = function() {
		imgData = {
			width: imgLoader.width,
			height: imgLoader.height,
			aspectRatio: imgLoader.width / imgLoader.height,
			src: imgLoader.src
		};
	};
	var preloadImg = function(url, done) {
		imgLoader = new Image();
		imgLoader.addEventListener('load', done, false);
		imgLoader.src = url;
	};
	init();
};

使用:

html節點:

     <div class="md-10" id="J_photo">
                   <img src="temp/p9-9.jpg" alt="" height="100%"  data-width="2000" class="bigwidth">
               </div>

js呼叫

PhotoTilt({
            'url': 'temp/p9-9.jpg',
            'container': document.getElementById('J_photo')
        });

css樣式:

.md10{position: absolute;left:0;width: 100%;height: 100%;overflow:hidden;}