Js动画基础

再谈js拖拽(二)仿iGoogle自定义首页模块拖拽的最后,我说了接下来要写Js动画,转瞬拖到了今天,呵呵。这篇主要讲动画的基础,就是几个最基本的特效,即:移动,渐变和尺寸变化。接下来写个梦幻西游版逍遥生角色行走的动画,然后再适时的写些动画有关的例子,争取把这个系列写好。

  我们玩魔兽世界的时候可以通过ctrl+r来查看当前的帧数,当帧数很小时,会觉得很卡,帧数很高则很流畅。所谓帧数就是1秒内显示图片的数量。当这么多帧图片连起来显示,就形成了动画。

  Js中实现动画都是靠setInterval或者setTimeout来实现。setInterval自身就能不断循环来执行计算从而显示新的帧,setTimeout是间隔一段时间后仅执行一次,他需要配合函数循环实现,很多人偏爱setTimeout来实现。本文采用setInterval实现。

  据说,普通人眼能看到1/24秒,就是说1秒至少24帧,每次移位间隔需要小于1000/24=41.7毫秒,也就说setInterval要每隔至少40毫秒执行一次,一般地,我们采用10毫秒,当然间隔时间越短,客户端执行计算次数就越多,如果你code计算量大则可以适当调长些。

  首先贴上封装好的动画类Animation。  

Animation
Animation = {
timer:
10,
SetOpacity:
function(obj, n) {
if (document.all) {
obj.filters.alpha.opacity
= n;
}
else {
obj.style.opacity
= n / 100;
}
},
fade:
function(obj, target, count, Func) {
obj
= this.getItself(obj);
var currentCount = 0;
count
= Math.abs(count) || 1;
target
= target < 0 ? 0 : (target > 100) ? 100 : target;
var init = document.all ? obj.filters.alpha.opacity : window.getComputedStyle(obj, null).opacity * 100;
Func
= Func || Tween.Linear;
var opr = this;
var flag = setInterval(function() {
if (currentCount > count) {
clearInterval(flag);
}
else {
currentCount
++;
var tmp = Func(init, target, currentCount, count);
opr.SetOpacity(obj, tmp);
//清除小数点的误差
if (Math.abs(tmp - target) < 1) {
opr.SetOpacity(obj, target);
}
}
}
,
this.timer);
},
resize:
function(obj, targetPos, count, Func) {
obj
= this.getItself(obj);
var currentCount = 0;
count
= Math.abs(count) || 1;
var initPos = { x: obj.offsetWidth, y: obj.offsetHeight }
Func
= Func || Tween.Linear;
targetPos
= { x: targetPos.x < 0 ? 0 : targetPos.x, y: targetPos.y < 0 ? 0 : targetPos.y }
var flag = setInterval(function() {
if (currentCount > count) {
clearInterval(flag);
}
else {
currentCount
++;
var tmpX = Func(initPos.x, targetPos.x, currentCount, count);
var tmpY = Func(initPos.y, targetPos.y, currentCount, count);
//width值不能小于0,但是算法返回值有可能出现负值
try {
obj.style.width
= tmpX + "px";
obj.style.height
= tmpY + "px";
}
catch (e) {
}
//清除小数点的误差
if (Math.abs(tmpX - targetPos.x) < 1) {
obj.style.width
= targetPos.x + "px";
}
if (Math.abs(tmpY - targetPos.y) < 1) {
obj.style.height
= targetPos.y + "px";
}
}
}
,
this.timer);
},
move:
function(obj, targetPos, count, Func) {
obj
= this.getItself(obj);
var currentCount = 0;
count
= Math.abs(count) || 1;
var elPos = this.getElementPos(obj);
var initPos = { x: elPos.x, y: elPos.y }
Func
= Func || Tween.Linear;
var flag = setInterval(function() {
if (currentCount > count) {
clearInterval(flag);
}
else {
currentCount
++;
var tmpX = Func(initPos.x, targetPos.x, currentCount, count);
var tmpY = Func(initPos.y, targetPos.y, currentCount, count);
obj.style.left
= tmpX + "px";
obj.style.top
= tmpY + "px";
//清除小数点的误差
if (Math.abs(tmpX - targetPos.x) < 1) {
obj.style.left
= targetPos.x + "px";
}
if (Math.abs(tmpY - targetPos.y) < 1) {
obj.style.top
= targetPos.y + "px";
}
}
}
,
this.timer);
},
getElementPos:
function(el) {
el
= this.getItself(el);
var _x = 0, _y = 0;
do {
_x
+= el.offsetLeft;
_y
+= el.offsetTop;
}
while (el = el.offsetParent);
return { x: _x, y: _y };
},
getItself:
function(id) {
return "string" == typeof id ? document.getElementById(id) : id;
}
}

  其中fade方法是实现渐变效果的,resize方法是改变对象尺寸大小的,move方法是实现移动效果的。首先看下move方法,其他2个方法实现其实是类似的。

  move方法的调用:Animation.move('divObj',{x:500,y:500},100,Tween.Quart.easeInOut); 第一个参数是移动的对象,第二个参数是移动的目标坐标,第三个参数是一共执行多少次移位,即移动时间内一共的帧数,即执行多少次,第4个参数是可选参数,指定Tween具体算法,若不加,则默认采用Tween.Linear。

  移动问题的关键就是每次移位后,应该将移动对象定位到什么位置,即其left和top是多少。来看一个简单的数学题,当我们知道了一个点的起始位置initPos和终点位置targetPos,要求在count次移动后达到终点,该点为匀速运动,求第currentCount次移动后该点位置在哪里?显然的位置在:(targetPos - initPos)*(currentCount/count)+initPos。这个就是Tween.Linear算法。当这个点不是匀速运动时,就是Tween的其他算法。Tween来自Flash的AS,你可以参考http://www.robertpenner.com/easing/easing_demo.html去查看Tween各种算法的运动效果,也可以参考cloudgamer的一篇文章JavaScript Tween算法及缓动效果。相比下,我将Tween各种算法的传入参数稍改了下,将移动的总距离的运算放到了Tween算法内部,然后最后个参数是作为总共计算次数理解的,而不是持续时间。我本来是想用持续时间运算的,但是发现还是要将持续时间除以10毫秒得到总次数,然后参与运算,总次数还可能非整数,有误差,所以我干脆直接传总次数过来,当然你也可以改成持续时间。那在应用时,究竟移动次数应该写多少,在每次间隔10毫秒进行移动下,次数越多,耗时越长。譬如采用Tween.Linear计算移动位置时,大概是耗时count*10ms的1.5倍,譬如写100,就是100*10*1.5=1.5s左右,这个多出来的0.5倍是Tween.Linear计算花费的时间。贴上改写后的Tween。   

Tween
/*
t:currentCount 当前执行第t次
b:initPos 初始值
c:targetPos - initPos 发生偏移的距离值
d:count 一共执行d次
效果:http://www.robertpenner.com/easing/easing_demo.html
JavaScript Tween算法及缓动效果 http://www.cnblogs.com/cloudgamer/archive/2009/01/06/tween.html
*/
var Tween = {
Linear:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return c * t / d + b;
},
Quad: {
easeIn:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return c * (t /= d) * t + b;
},
easeOut:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return -c * (t /= d) * (t - 2) + b;
},
easeInOut:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
if ((t /= d / 2) < 1) return c / 2 * t * t + b;
return -c / 2 * ((--t) * (t - 2) - 1) + b;
}
},
Cubic: {
easeIn:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return c * (t /= d) * t * t + b;
},
easeOut:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return c * ((t = t / d - 1) * t * t + 1) + b;
},
easeInOut:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
if ((t /= d / 2) < 1) return c / 2 * t * t * t + b;
return c / 2 * ((t -= 2) * t * t + 2) + b;
}
},
Quart: {
easeIn:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return c * (t /= d) * t * t * t + b;
},
easeOut:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return -c * ((t = t / d - 1) * t * t * t - 1) + b;
},
easeInOut:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b;
return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
}
},
Quint: {
easeIn:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return c * (t /= d) * t * t * t * t + b;
},
easeOut:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
},
easeInOut:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b;
return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
}
},
Sine: {
easeIn:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;
},
easeOut:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return c * Math.sin(t / d * (Math.PI / 2)) + b;
},
easeInOut:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b;
}
},
Expo: {
easeIn:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b;
},
easeOut:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
},
easeInOut:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
if (t == 0) return b;
if (t == d) return b + c;
if ((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
}
},
Circ: {
easeIn:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b;
},
easeOut:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return c * Math.sqrt(1 - (t = t / d - 1) * t) + b;
},
easeInOut:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
if ((t /= d / 2) < 1) return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b;
return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b;
}
},
Elastic: {
easeIn:
function(initPos, targetPos, currentCount, count, a, p) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3;
if (!a || a < Math.abs(c)) { a = c; var s = p / 4; }
else var s = p / (2 * Math.PI) * Math.asin(c / a);
return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
},
easeOut:
function(initPos, targetPos, currentCount, count, a, p) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3;
if (!a || a < Math.abs(c)) { a = c; var s = p / 4; }
else var s = p / (2 * Math.PI) * Math.asin(c / a);
return (a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b);
},
easeInOut:
function(initPos, targetPos, currentCount, count, a, p) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
if (t == 0) return b; if ((t /= d / 2) == 2) return b + c; if (!p) p = d * (.3 * 1.5);
if (!a || a < Math.abs(c)) { a = c; var s = p / 4; }
else var s = p / (2 * Math.PI) * Math.asin(c / a);
if (t < 1) return -.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
}
},
Back: {
easeIn:
function(initPos, targetPos, currentCount, count, s) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
if (s == undefined) s = 1.70158;
return c * (t /= d) * t * ((s + 1) * t - s) + b;
},
easeOut:
function(initPos, targetPos, currentCount, count, s) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
if (s == undefined) s = 1.70158;
return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
},
easeInOut:
function(initPos, targetPos, currentCount, count, s) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
if (s == undefined) s = 1.70158;
if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
}
},
Bounce: {
easeIn:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return c - Tween.Bounce.easeOut(d - t, 0, c, d) + b;
},
easeOut:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
if ((t /= d) < (1 / 2.75)) {
return c * (7.5625 * t * t) + b;
}
else if (t < (2 / 2.75)) {
return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
}
else if (t < (2.5 / 2.75)) {
return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
}
else {
return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
}
},
easeInOut:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
if (t < d / 2) return Tween.Bounce.easeIn(t * 2, 0, c, d) * .5 + b;
else return Tween.Bounce.easeOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
}
}
}

  相比move方法,fade方法是用Tween算法去计算透明度,而resize方法是用Tween算法去计算width和height,没有大的区别。利用这3个特效,一些简单的动画都能实现了。如果某对象要在移动过程中同时改变大小和设置透明度,只要三个方法连续写下来即可。如:

<input type="button" value="Move&Resize&SetOpacity" onclick="Animation.fade('divObj',50,100);Animation.resize('divObj',{x:300,y:200},100);Animation.move('divObj',{x:100,y:100},100);" />

(ps:若无特别声明,此博客所有例子均可在IE/FF/Chrome中运行)

点击下载

背景:梦幻西游;人物:逍遥生;场景:北俱芦洲。

  游览行为:点击鼠标,人物行走。右键也能使人物转向。由于我只找到了人物四个方向的素材,所以如果刚好正对人物位置的水平或垂直方向,走起来会有些别扭,如果用八方图,code上只要再加正东南西北四个方向即可。一共使用了2张图片,一张是人物的四方图,一张是场景图,场景图用于设为body背景。

  贴上一部分效果图,你可以在本文结尾下载整个demo

  

  先贴上Common类,主要就是通用的操作,如取元素位置,取鼠标位置,我的很多文章里都用到的。  

Common

  贴上Walker类,  

代码
<script type="text/javascript">
var Class = {
create:
function() {
return function() { this.init.apply(this, arguments); }
}
}
var Walker = Class.create();
Walker.prototype
= {
init:
function(_src, _walkerSize, initPos) {
//人物朝向,值与人物图片的行数要对应。譬如说图片第1行是朝向SouthWest的,则this.direction.SouthWest值为1
this.direction = { SouthEast: 0, SouthWest: 1, NorthEast: 2, NorthWest: 3 };
this.currentDirection = this.direction.SouthEast; //当前人物朝向
this.speed = 0.5; //默认速度:每次移动0.5px 通过此和起点终点距离算出移动总次数(总帧数)
this.walkFlag = this.moveFlag = null;
this.walkerSize = _walkerSize;
this.walker = document.createElement("div");
this.walker.style.cssText = "position:absolute;" + this.walkerSize.w + ";height:" + this.walkerSize.h + ";clip:rect(0px " + this.walkerSize.w + "px " + this.walkerSize.h + "px 0px)";
document.body.appendChild(
this.walker);

this.img = document.createElement("img");
this.img.src = _src;
this.img.style.position = "absolute";
this.walker.appendChild(this.img);

this.walker.style.left = initPos.x + "px";
this.walker.style.top = initPos.y + "px";
},
setWalkStatus:
function(row, col) {//col=0设置为该方向的初始状态。row值与方向direction一致
this.img.style.left = -col * this.walkerSize.w + "px";
this.img.style.top = -row * this.walkerSize.h + "px";
},
getDirection:
function(mousePos) {
var dir = 0;
var initPos = Common.getElementPos(this.walker);
initPos.x
= initPos.x + this.walkerSize.w / 2, initPos.y = initPos.y + this.walkerSize.h / 2;
if (mousePos.y < initPos.y) {//上方
if (mousePos.x > initPos.x) { //东北
dir = this.direction.NorthEast;
}
else { //西北
dir = this.direction.NorthWest;
}
}
else { //下方
if (mousePos.x > initPos.x) { //东南
dir = this.direction.SouthEast;
}
else { //西南
dir = this.direction.SouthWest;
}
}
this.currentDirection = dir;
},
beginWalk:
function(mousePos) {
this.getDirection(mousePos);
var row = this.currentDirection;
this.setWalkStatus(row, 1);
var walkerObj = this;
var tmp = 1;
this.walkFlag = setInterval(function() {
tmp
= tmp > 3 ? 0 : tmp;
//walkerObj.img.style.left = -walkerObj.walkerSize.w * tmp + "px";
walkerObj.setWalkStatus(row, tmp);
tmp
++;
},
200);
},
stopWalk:
function() {
clearInterval(
this.walkFlag);
clearInterval(
this.moveFlag);
this.setWalkStatus(this.currentDirection, 0);
},
walk:
function(e) {
//停止当前动作
this.stopWalk();
var mousePos = Common.getMousePos(e);
this.beginWalk(mousePos);
this.move(this.walker, { x: mousePos.x - this.walkerSize.w / 2, y: mousePos.y - this.walkerSize.h / 2 });
},
setDirection:
function(e) {
this.getDirection(Common.getMousePos(e));
this.setWalkStatus(this.currentDirection, 0);
},
timer:
10,
move:
function(obj, targetPos) {
var currentCount = 0;
var elPos = Common.getElementPos(obj);
var initPos = { x: elPos.x, y: elPos.y }
var distance = Math.sqrt(Math.abs(targetPos.x - initPos.x) * Math.abs(targetPos.x - initPos.x) + Math.abs(targetPos.y - initPos.y) * Math.abs(targetPos.y - initPos.y));
var count = Math.ceil(distance / this.speed);
var tmpWalkObj = this;
var Func = Tween.Linear;
this.moveFlag = setInterval(function() {
if (currentCount > count) {
tmpWalkObj.stopWalk();
}
else {
currentCount
++;
var tmpX = Func(initPos.x, targetPos.x, currentCount, count);
var tmpY = Func(initPos.y, targetPos.y, currentCount, count);
obj.style.left
= tmpX + "px";
obj.style.top
= tmpY + "px";
//清除小数点的误差
if (Math.abs(tmpX - targetPos.x) < 1) {
obj.style.left
= targetPos.x + "px";
}
if (Math.abs(tmpY - targetPos.y) < 1) {
obj.style.top
= targetPos.y + "px";
}
//边界控制
if (parseInt(obj.style.left) < 0) {
obj.style.left
= 0 + "px";
}
if (parseInt(obj.style.top) < 0) {
obj.style.top
= 0 + "px";
}
if (parseInt(obj.style.left) + tmpWalkObj.walkerSize.w > 1024) {//场景图片尺寸:1024*764
tmpWalkObj.stopWalk();
}
if (parseInt(obj.style.top) + tmpWalkObj.walkerSize.h > 764) {
tmpWalkObj.stopWalk();
}
}
}
,
this.timer);
}
}

var Tween = {
Linear:
function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return c * t / d + b;
}
}
</script>

  人物行走如何实现呢?3步。

  在这3步之前,当然会用init方法初始化1个div做为容器,来存放这个人物图片,所谓的人物行走就是这个div在移动。(细节见code的注释)

  1. 显示人物四方图的某一块小图。

  本例的四方图是4*4=16个人物形态构成,就是要显示具体的1个人物形态。实现方法:setWalkStatus。由于外部容器div的尺寸只是1个人物形态的尺寸,通过设置人物图片的left和top值,就能显示图片中第row行第col列的人物。

  2.让人物动起来。

  实现方法:beginWalk。通过setInterval循环执行setWalkStatus方法就能实现同一行的四个动作连贯显示。人物就动起来了。

  3.让动起来的人物移动。

  鼠标点击后移动,要首先算出朝哪个方向移动,从而显示那个方向的人物图片,方法:getDirection。

  移动的主要code在move方法里。如何move和Js动画(一)基础所说的move原理一样,但是又不能照搬,因为那里的move是自己设置总帧数从而控制时间,达到设置移动快慢的目的。而这里,人物的移动肯定永远是匀速的,行走的距离长自然执行的总次数多,时间也就越长。所以原先自定义的count数要算出来,移动总次数=人物行走的总距离(像素)/速度(每1次移动speed像素),其他照旧。然后添加一些人物移动的边界限制。

  文档加载后初始化逍遥生及注册逍遥生行为事件。  

代码
<script type="text/javascript">
window.onload
= function() {
var 逍遥生 = new Walker("walker2.png", { w: 70, h: 92 }, { x: 100, y: 50 });
document.documentElement.onclick
= function(e) {
逍遥生.walk(e);
}
document.documentElement.oncontextmenu
= function(e) {
if (document.all) {
window.event.returnValue
= false;
}
else {
if (e.preventDefault) {
e.preventDefault();
e.stopPropagation();
}
}
逍遥生.setDirection(e);
}
}
</script>

  其中,var 逍遥生 = new Walker("walker2.png", { w: 70, h: 92 }, { x: 100, y: 50 }); 第一个参数是人物图片,第二个参数是单个人物形态尺寸,70=图片宽度280/4,第三个参数是,人物的出生地。

  毕了。

  点击下载

原文地址:https://www.cnblogs.com/Leo_wl/p/1764999.html