`
rockyuse
  • 浏览: 191255 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

使用requestAnimationFrame更好的实现javascript动画(转)

 
阅读更多
详细说明:http://www.cnblogs.com/rubylouvre/archive/2011/08/22/2148793.html

function animate(element, name, from, to, time) {
	time = time || 800; // 默认0.8秒
	var style = element.style;

	var latency = 13; // 时间间隔 每13ms一次变化
	var count = parseInt(time / latency); // 变化的次数
	var step = Math.round((to - from) / count); // 步长 每一步的变化量
	var now = from;

	function go() {
		count--;
		now = count ? now + step : to;
		style[name] = now + 'px';
		if (count) {
			setTimeout(go, latency);
		}
	}

	style[name] = from + 'px';
	setTimeout(go, latency);
}

var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame ||
function (callback) {
	setTimeout(callback, 1000 / 60);
};

function animate1(element, name, from, to, time) {
	time = time || 800; // 默认0.8秒
	var startTime = new Date;

	function go(timestamp) {
		console.log(timestamp)

		var progress = timestamp - startTime;
		if (progress >= time) {
			element.style[name] = to + 'px';
			return;
		}

		var now = (to - from) * (progress / time);
		element.style[name] = now.toFixed() + 'px';

		//console.log(now.toFixed())
		requestAnimationFrame(go);
	}

	element.style[name] = from + 'px';

	requestAnimationFrame(go);
}

//animate1(document.getElementById('holder'), 'marginLeft', 0, 180, 500)

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics