Maison  >  Article  >  interface Web  >  Exemples pour expliquer l'animation d'image javascript

Exemples pour expliquer l'animation d'image javascript

巴扎黑
巴扎黑original
2017-09-04 10:12:291291parcourir

L'éditeur suivant vous apportera une animation de frame javascript (explication avec exemples). L'éditeur le trouve plutôt bon, je vais donc le partager avec vous maintenant et le donner comme référence pour tout le monde. Suivons l'éditeur et jetons un coup d'œil.

Comme mentionné précédemment

L'animation par image consiste à décomposer les actions d'animation en "images clés continues", c'est-à-dire qu'il s'agit d'une animation qui dessine un contenu différent image par image sur chaque image de la chronologie et le lit en continu. Parce qu'elle est dessinée image par image, l'animation image a une grande flexibilité et peut exprimer presque tout le contenu que vous souhaitez exprimer. Cet article présentera en détail l'animation du cadre javascript

Aperçu

[Classification]

Il existe trois méthodes courantes de animation de cadre, y compris gif, animation CSS3 et javascript

git et animation CSS3 ne peuvent pas contrôler de manière flexible la pause et la lecture de l'animation, et ne peuvent pas étendre de manière flexible l'animation de cadre. De plus, les images GIF ne peuvent pas capturer l’événement de fin de l’animation. Par conséquent, utilisez généralement javascript pour implémenter l'animation de cadre

[Principe]

Il existe deux façons d'implémenter l'animation de cadre à l'aide de js

1. Si vous avez plusieurs images d'animation d'images, vous pouvez utiliser une balise d'image pour transporter l'image et modifier régulièrement l'attribut src de l'image (non recommandé)

2. Dessinez toutes les images clés d'animation dans une seule image, et mettez l'image Comme image d'arrière-plan de l'élément, modifiez régulièrement l'attribut background-position de l'élément (recommandé)

Étant donné que la première méthode nécessite plusieurs requêtes HTTP, il est généralement recommandé d'utiliser la deuxième méthode

[Exemple]

Ce qui suit est un exemple d'utilisation de l'animation de cadre


<p id="rabbit" ></p> 
<button id="btn">暂停运动</button> 
<script>
var url = &#39;rabbit-big.png&#39;;
var positions = [&#39;0,-854&#39;,&#39;-174 -852&#39;,&#39;-349 -852&#39;,&#39;-524 -852&#39;,&#39;-698 -852&#39;,&#39;-873 -848&#39;];
var ele = document.getElementById(&#39;rabbit&#39;);
var oTimer = null;
btn.onclick = function(){
 if(btn.innerHTML == &#39;开始运动&#39;){
  frameAnimation(ele,positions,url);
  btn.innerHTML = &#39;暂停运动&#39;;
 }else{
  clearTimeout(oTimer);
  btn.innerHTML = &#39;开始运动&#39;;
 } 
}
frameAnimation(ele,positions,url);
function frameAnimation(ele,positions,url){
 ele.style.backgroundImage = &#39;url(&#39; + url + &#39;)&#39;;
 ele.style.backgroundRepeat = &#39;no-repeat&#39;; 
 var index = 0;
 function run(){
  var pos = positions[index].split(&#39; &#39;);
  ele.style.backgroundPosition = pos[0] + &#39;px &#39; + pos[1] + &#39;px&#39;;
  index++;
  if(index >= positions.length){
   index = 0;
  }
  oTimer = setTimeout(run,80);
 }
 run();
} 
</script>

Cadre général animation

Concevons une bibliothèque générale d'animation d'images

[Analyse des exigences]

 1. Prise en charge du préchargement d'images

 2. Prise en charge deux types Méthode de lecture d'animation et personnalisation de chaque image d'animation

3. Prend en charge les temps de boucle de contrôle d'animation d'un seul groupe (peut prendre en charge des durées illimitées)

4. Prend en charge l'achèvement d'un ensemble d'animations et la prochaine série d'animations

5. Prise en charge du temps d'attente une fois chaque animation terminée

6. Prise en charge de la pause de l'animation et reprise de la lecture

7. Prise en charge de l'exécution de la fonction de rappel après l'animation est terminée

【Interface de programmation】

1. loadImage(imglist)//Précharger l'image

2. changer la position d'arrière-plan de l'élément

3. changeSrc(ele,imglist)//En changeant le src de l'élément image

4. enterFrame(callback)//La fonction exécutée par chaque image d'animation est équivalente au rappel défini par l'utilisateur pour chaque image d'animation

5. répéter(fois)//Le nombre de fois que l'animation est répétée Lorsque times est vide, cela signifie un nombre illimité de fois<.>

6. repeatForever()//Répéter la dernière fois à l'infini Animation, équivalent à repeat()

7 wait(time)//Le temps d'attente après la fin de chaque exécution d'animation

8. then(callback)//Callback une fois l'exécution de l'animation terminée Fonction

9. start(interval)//L'animation commence à s'exécuter, l'intervalle représente l'intervalle entre les exécutions de l'animation

10. pause()//L'animation fait une pause

11. restart()//L'animation est réexécutée à partir du point de pause précédent

12. disposer()//Libérer les ressources.

[Méthode d'appel]

Prend en charge les appels en chaîne, en utilisant des verbes Décrire l'interface d'une manière

[Conception de code]

1 Traitez une série de. des opérations telles que le préchargement d'images -> l'exécution de l'animation -> la fin de l'animation en tant que chaîne de tâches. La chaîne de tâches comprend deux types de tâches : l'exécution synchrone et l'exécution planifiée asynchrone

2. Enregistrez l'index de la chaîne de tâches actuelle

3. Après l'exécution de chaque tâche, la tâche suivante est exécutée en appelant la méthode suivante et mettez à jour la valeur de l'index de la chaîne de tâches

[Définition de l'interface]


&#39;use strict&#39;;
/* 帧动画库类
 * @constructor
 */
function FrameAnimation(){}

/* 添加一个同步任务,去预加载图片
 * @param imglist 图片数组
 */
FrameAnimation.prototype.loadImage = function(imglist){}

/* 添加一个异步定时任务,通过定时改变图片背景位置,实现帧动画
 * @param ele dom对象
 * @param positions 背景位置数组
 * @param imageUrl 图片URL地址
 */
FrameAnimation.prototype.changePosition = function(ele,positions,imageUrl){}

/* 添加一个异步定时任务,通过定时改变image标签的src属性,实现帧动画
 * @param ele dom对象
 * @param imglist 图片数组
 */
FrameAnimation.prototype.changeSrc = function(ele,imglist){}

/* 添加一个异步定时任务,自定义动画每帧执行的任务函数
 * @param tastFn 自定义每帧执行的任务函数
 */
FrameAnimation.prototype.enterFrame = function(taskFn){}

/* 添加一个同步任务,在上一个任务完成后执行回调函数
 * @param callback 回调函数
 */
FrameAnimation.prototype.then = function(callback){}

/* 开始执行任务,异步定时任务执行的间隔
 * @param interval
 */
FrameAnimation.prototype.start = function(interval){}

/* 添加一个同步任务,回退到上一个任务,实现重复上一个任务的效果,可以定义重复的次数
 * @param times 重复次数
 */
FrameAnimation.prototype.repeat = function(times){}

/* 添加一个同步任务,相当于repeat(),无限循环上一次任务
 * 
 */
FrameAnimation.prototype.repeatForever = function(){}

/* 设置当前任务执行结束后到下一个任务开始前的等待时间
 * @param time 等待时长
 */
FrameAnimation.prototype.wait = function(time){}

/* 暂停当前异步定时任务
 * 
 */
FrameAnimation.prototype.pause = function(){}

/* 重新执行上一次暂停的异步定时任务
 * 
 */
FrameAnimation.prototype.restart = function(){}

/* 释放资源
 * 
 */
FrameAnimation.prototype.dispose = function(){}

Préchargement d'images

Le préchargement d'images est une fonction relativement indépendante, qui peut être encapsulée dans un module imageloader.js


&#39;use strict&#39;;
/**
 * 预加载图片函数
 * @param  images  加载图片的数组或者对象
 * @param  callback 全部图片加载完毕后调用的回调函数
 * @param  timeout 加载超时的时长
 */
function loadImage(images,callback,timeout){
 //加载完成图片的计数器
 var count = 0;
 //全部图片加载成功的标志位
 var success = true;
 //超时timer的id
 var timeoutId = 0;
 //是否加载超时的标志位
 var isTimeout = false;
 //对图片数组(或对象)进行遍历
 for(var key in images){
  //过滤prototype上的属性
  if(!images.hasOwnProperty(key)){
   continue;
  }
  //获得每个图片元素
  //期望格式是object:{src:xxx}
  var item = images[key];
  if(typeof item === &#39;string&#39;){
   item = images[key] = {
    src:item
   };
  }
  //如果格式不满足期望,则丢弃此条数据,进行下一次遍历
  if(!item || !item.src){
   continue;
  }
  //计数+1
  count++;
  //设置图片元素的id
  item.id = &#39;__img__&#39; + key + getId();
  //设置图片元素的img,它是一个Image对象
  item.img = window[item.id] = new Image();
  doLoad(item);
 }
 //遍历完成如果计数为0,则直接调用callback
 if(!count){
  callback(success);
 }else if(timeout){
  timeoutId = setTimeout(onTimeout,timeout);
 }

 /**
  * 真正进行图片加载的函数
  * @param  item 图片元素对象
  */
 function doLoad(item){
  item.status = &#39;loading&#39;;
  var img = item.img;
  //定义图片加载成功的回调函数
  img.onload = function(){
   success = success && true;
   item.status = &#39;loaded&#39;;
   done();
  }
  //定义图片加载失败的回调函数
  img.onerror = function(){
   success = false;
   item.status = &#39;error&#39;;
   done();
  }
  //发起一个http(s)请求
  img.src = item.src;
  /**
   * 每张图片加载完成的回调函数
   */
  function done(){
   img.onload = img.onerror = null;
   try{
    delete window[item.id];
   }catch(e){

   }
   //每张图片加载完成,计数器减1,当所有图片加载完成,且没有超时的情况,清除超时计时器,且执行回调函数
   if(!--count && !isTimeout){
    clearTimeout(timeoutId);
    callback(success);
   }
  }
 }
 /**
  * 超时函数
  */
 function onTimeout(){
  isTimeout = true;
  callback(false);
 }
}
var __id = 0;
function getId(){
 return ++__id;
}
module.exports = loadImage;

Timeline

Dans le traitement de l'animation, il est implémenté en utilisant setTimeout() de manière itérative, mais cet intervalle n'est pas précis. Ensuite, implémentez une classe de chronologie timeline.js


&#39;use strict&#39;;

var DEFAULT_INTERVAL = 1000/60;

//初始化状态
var STATE_INITIAL = 0;
//开始状态
var STATE_START = 1;
//停止状态
var STATE_STOP = 2;

var requestAnimationFrame = (function(){
 return window.requestAnimationFrame || window.webkitRequestAnimationFrame|| window.mozRequestAnimationFrame || window.oRequestAnimationFrame || function(callback){
     return window.setTimeout(callback,(callback.interval || DEFAULT_INTERVAL));
    }
})();

var cancelAnimationFrame = (function(){
 return window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.oCancelAnimationFrame  || function(id){
     return window.clearTimeout(id);
    } 
})();
/**
 * 时间轴类
 * @constructor
 */
function Timeline(){
 this.animationHandler = 0;
 this.state = STATE_INITIAL;
}
/**
 * 时间轴上每一次回调执行的函数
 * @param  time 从动画开始到当前执行的时间
 */
Timeline.prototype.onenterframe = function(time){

}
/**
 * 动画开始
 * @param interval 每一次回调的间隔时间
 */
Timeline.prototype.start = function(interval){
 if(this.state === STATE_START){
  return;
 }
 this.state = STATE_START;
 this.interval = interval || DEFAULT_INTERVAL;
 startTimeline(this,+new Date());
}

/**
 * 动画停止
 */
Timeline.prototype.stop = function(){
 if(this.state !== STATE_START){
  return;
 }
 this.state = STATE_STOP;
 //如果动画开始过,则记录动画从开始到现在所经历的时间
 if(this.startTime){
  this.dur = +new Date() - this.startTime;
 }
 cancelAnimationFrame(this.animationHandler);
}

/**
 * 重新开始动画
 */
Timeline.prototype.restart = function(){
 if(this.state === STATE_START){
  return;
 }
 if(!this.dur || !this.interval){
  return;
 }
 this.state = STATE_START;
 //无缝连接动画
 startTimeline(this,+new Date()-this.dur);
}

/**
 * 时间轴动画启动函数
 * @param  timeline 时间轴的实例
 * @param  startTime 动画开始时间戳     
 */
function startTimeline(timeline,startTime){
 //记录上一次回调的时间戳
 var lastTick = +new Date();
 timeline.startTime = startTime;
 nextTick.interval = timeline.interval;
 nextTick();
 /**
  * 每一帧执行的函数
  */
 function nextTick(){
  var now = +new Date();
  timeline.animationHandler = requestAnimationFrame(nextTick);
  //如果当前时间与上一次回调的时间戳大于设置的时间间隔,表示这一次可以执行回调函数
  if(now - lastTick >= timeline.interval){
   timeline.onenterframe(now - startTime);
   lastTick = now;
  }
 }
}
module.exports = Timeline;

Implémentation de la classe d'animation

Ce qui suit est le code complet de la classe d'animation animation.js


&#39;use strict&#39;;

var loadImage = require(&#39;./imageloader&#39;);
var Timeline = require(&#39;./timeline&#39;);
//初始化状态
var STATE_INITIAL = 0;
//开始状态
var STATE_START = 1;
//停止状态
var STATE_STOP = 2;
//同步任务
var TASK_SYNC = 0;
//异步任务
var TASK_ASYNC = 1;

/**
 * 简单的函数封装,执行callback
 * @param  callback 执行函数
 */
function next(callback){
 callback && callback();
}
/* 帧动画库类
 * @constructor
 */
function FrameAnimation(){
 this.taskQueue = [];
 this.index = 0;
 this.timeline = new Timeline();
 this.state = STATE_INITIAL;
}

/* 添加一个同步任务,去预加载图片
 * @param imglist 图片数组
 */
FrameAnimation.prototype.loadImage = function(imglist){
 var taskFn = function(next){
  loadImage(imglist.slice(),next);
 };
 var type = TASK_SYNC;
 return this._add(taskFn,type);
}

/* 添加一个异步定时任务,通过定时改变图片背景位置,实现帧动画
 * @param ele dom对象
 * @param positions 背景位置数组
 * @param imageUrl 图片URL地址
 */
FrameAnimation.prototype.changePosition = function(ele,positions,imageUrl){
 var len = positions.length;
 var taskFn;
 var type;
 if(len){
  var me = this;
  taskFn = function(next,time){
   if(imageUrl){
    ele.style.backgroundImage = &#39;url(&#39; + imageUrl + &#39;)&#39;;
   }
   //获得当前背景图片位置索引
   var index = Math.min(time/me.interval|0,len);
   var position = positions[index-1].split(&#39; &#39;);
   //改变dom对象的背景图片位置
   ele.style.backgroundPosition = position[0] + &#39;px &#39; + position[1] + &#39;px&#39;;
   if(index === len){
    next();
   }
  }
  type = TASK_ASYNC;
 }else{
  taskFn = next;
  type = TASK_SYNC;
 }
 return this._add(taskFn,type);
}

/* 添加一个异步定时任务,通过定时改变image标签的src属性,实现帧动画
 * @param ele dom对象
 * @param imglist 图片数组
 */
FrameAnimation.prototype.changeSrc = function(ele,imglist){
 var len = imglist.length;
 var taskFn;
 var type;
 if(len){
  var me = this;
  taskFn = function(next,time){
   //获得当前背景图片位置索引
   var index = Math.min(time/me.interval|0,len);
   //改变image对象的背景图片位置
   ele.src = imglist[index-1];
   if(index === len){
    next();
   }
  }
  type = TASK_ASYNC;
 }else{
  taskFn = next;
  type = TASK_SYNC;
 }
 return this._add(taskFn,type); 
}

/* 添加一个异步定时任务,自定义动画每帧执行的任务函数
 * @param tastFn 自定义每帧执行的任务函数
 */
FrameAnimation.prototype.enterFrame = function(taskFn){
 return this._add(taskFn,TASK_ASYNC);
}

/* 添加一个同步任务,在上一个任务完成后执行回调函数
 * @param callback 回调函数
 */
FrameAnimation.prototype.then = function(callback){
 var taskFn = function(next){
  callback(this);
  next();
 };
 var type = TASK_SYNC;
 return this._add(taskFn,type);
}

/* 开始执行任务,异步定义任务执行的间隔
 * @param interval
 */
FrameAnimation.prototype.start = function(interval){
 if(this.state === STATE_START){
  return this; 
 }
 //如果任务链中没有任务,则返回
 if(!this.taskQueue.length){
  return this;
 }
 this.state = STATE_START;
 this.interval = interval;
 this._runTask();
 return this;
  
}

/* 添加一个同步任务,回退到上一个任务,实现重复上一个任务的效果,可以定义重复的次数
 * @param times 重复次数
 */
FrameAnimation.prototype.repeat = function(times){
 var me = this;
 var taskFn = function(){
  if(typeof times === &#39;undefined&#39;){
   //无限回退到上一个任务
   me.index--;
   me._runTask();
   return;
  }
  if(times){
   times--;
   //回退
   me.index--;
   me._runTask();
  }else{
   //达到重复次数,跳转到下一个任务
   var task = me.taskQueue[me.index];
   me._next(task);
  }
 }
 var type = TASK_SYNC;
 return this._add(taskFn,type);
}

/* 添加一个同步任务,相当于repeat(),无限循环上一次任务
 * 
 */
FrameAnimation.prototype.repeatForever = function(){
 return this.repeat();
}

/* 设置当前任务执行结束后到下一个任务开始前的等待时间
 * @param time 等待时长
 */
FrameAnimation.prototype.wait = function(time){
 if(this.taskQueue && this.taskQueue.length > 0){
  this.taskQueue[this.taskQueue.length - 1].wait = time;
 }
 return this;
}

/* 暂停当前异步定时任务
 * 
 */
FrameAnimation.prototype.pause = function(){
 if(this.state === STATE_START){
  this.state = STATE_STOP;
  this.timeline.stop();
  return this;
 }
 return this;
}

/* 重新执行上一次暂停的异步定时任务
 * 
 */
FrameAnimation.prototype.restart = function(){
 if(this.state === STATE_STOP){
  this.state = STATE_START;
  this.timeline.restart();
  return this;
 }
 return this; 
}

/* 释放资源
 * 
 */
FrameAnimation.prototype.dispose = function(){
 if(this.state !== STATE_INITIAL){
  this.state = STATE_INITIAL;
  this.taskQueue = null;
  this.timeline.stop();
  this.timeline = null;
  return this;
 }
 return this;  
}

/**
 * 添加一个任务到任务队列
 * @param taskFn 任务方法
 * @param type  任务类型
 * @private
 */
FrameAnimation.prototype._add = function(taskFn,type){
 this.taskQueue.push({
  taskFn:taskFn,
  type:type
 });
 return this;
}

/**
 * 执行任务
 * @private
 */
FrameAnimation.prototype._runTask = function(){
 if(!this.taskQueue || this.state !== STATE_START){
  return;
 }
 //任务执行完毕
 if(this.index === this.taskQueue.length){
  this.dispose();
  return;
 }
 //获得任务链上的当前任务
 var task = this.taskQueue[this.index];
 if(task.type === TASK_SYNC){
  this._syncTask(task);
 }else{
  this._asyncTask(task);
 }
}

/**
 * 同步任务
 * @param task 执行的任务对象
 * @private
 */
FrameAnimation.prototype._syncTask = function(task){
 var me = this;
 var next = function(){
  //切换到下一个任务
  me._next(task);
 }
 var taskFn = task.taskFn;
 taskFn(next);
}

/**
 * 异步任务
 * @param task 执行的任务对象
 * @private
 */
FrameAnimation.prototype._asyncTask = function(task){
 var me = this;
 //定义每一帧执行的回调函数
 var enterframe = function(time){
  var taskFn = task.taskFn;
  var next = function(){
   //停止当前任务
   me.timeline.stop();
   //执行下一个任务
   me._next(task);
  };
  taskFn(next,time);
 }
 this.timeline.onenterframe = enterframe;
 this.timeline.start(this.interval);
}

/**
 * 切换到下一个任务,支持如果当前任务需要等待,则延时执行
 * @private
 */
FrameAnimation.prototype._next = function(task){
 this.index++;
 var me = this;
 task.wait ? setTimeout(function(){
  me._runTask();
 },task.wait) : this._runTask();
}

module.exports = function(){
  return new FrameAnimation();
}

configuration du webpack

Dû La spécification du module AMD est utilisée dans la production de la bibliothèque d'animation de cadres d'animation, mais comme elle n'est pas prise en charge au niveau du navigateur, Webpack doit être utilisé pour la gestion modulaire, et animation.js, imageloader.js et timeline.js sont regroupés dans un seul fichier


module.exports = {
 entry:{
  animation:"./src/animation.js"
 },
 output:{
  path:__dirname + "/build",
  filename:"[name].js",
  library:"animation",
  libraryTarget:"umd",
 }
}
Ce qui suit est un exemple de code pour obtenir l'effet d'animation du démarrage du blog via la bibliothèque d'animation de cadres créée


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
</head>
<body>
<p id="rabbit" ></p> 
<script src="../build/animation.js"></script> 
<script>var imgUrl = &#39;rabbit-big.png&#39;;
var positions = [&#39;0,-854&#39;,&#39;-174 -852&#39;,&#39;-349 -852&#39;,&#39;-524 -852&#39;,&#39;-698 -852&#39;,&#39;-873 -848&#39;];
var ele = document.getElementById(&#39;rabbit&#39;);
var animation = window.animation;
var repeatAnimation = animation().loadImage([imgUrl]).changePosition(ele,positions,imgUrl).repeatForever();
repeatAnimation.start(80); 
</script>
</body>
</html>

Plus d'exemples

En plus d'obtenir l'effet d'un chariot à lapin, vous pouvez également utiliser une animation d'image pour obtenir l'effet effet de la victoire du lapin et de l'échec du lapin


Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn