animation.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import Sprite from './sprite'
  2. import DataBus from '../databus'
  3. let databus = new DataBus()
  4. const __ = {
  5. timer: Symbol('timer'),
  6. }
  7. /**
  8. * 简易的帧动画类实现
  9. */
  10. export default class Animation extends Sprite {
  11. constructor(imgSrc, width, height) {
  12. super(imgSrc, width, height)
  13. // 当前动画是否播放中
  14. this.isPlaying = false
  15. // 动画是否需要循环播放
  16. this.loop = false
  17. // 每一帧的时间间隔
  18. this.interval = 1000 / 60
  19. // 帧定时器
  20. this[__.timer] = null
  21. // 当前播放的帧
  22. this.index = -1
  23. // 总帧数
  24. this.count = 0
  25. // 帧图片集合
  26. this.imgList = []
  27. /**
  28. * 推入到全局动画池里面
  29. * 便于全局绘图的时候遍历和绘制当前动画帧
  30. */
  31. databus.animations.push(this)
  32. }
  33. /**
  34. * 初始化帧动画的所有帧
  35. * 为了简单,只支持一个帧动画
  36. */
  37. initFrames(imgList) {
  38. imgList.forEach((imgSrc) => {
  39. let img = new Image()
  40. img.src = imgSrc
  41. this.imgList.push(img)
  42. })
  43. this.count = imgList.length
  44. }
  45. // 将播放中的帧绘制到canvas上
  46. aniRender(ctx) {
  47. ctx.drawImage(
  48. this.imgList[this.index],
  49. this.x,
  50. this.y,
  51. this.width * 1.2,
  52. this.height * 1.2
  53. )
  54. }
  55. // 播放预定的帧动画
  56. playAnimation(index = 0, loop = false) {
  57. // 动画播放的时候精灵图不再展示,播放帧动画的具体帧
  58. this.visible = false
  59. this.isPlaying = true
  60. this.loop = loop
  61. this.index = index
  62. if ( this.interval > 0 && this.count ) {
  63. this[__.timer] = setInterval(
  64. this.frameLoop.bind(this),
  65. this.interval
  66. )
  67. }
  68. }
  69. // 停止帧动画播放
  70. stop() {
  71. this.isPlaying = false
  72. if ( this[__.timer] )
  73. clearInterval(this[__.timer])
  74. }
  75. // 帧遍历
  76. frameLoop() {
  77. this.index++
  78. if ( this.index > this.count - 1 ) {
  79. if ( this.loop ) {
  80. this.index = 0
  81. }
  82. else {
  83. this.index--
  84. this.stop()
  85. }
  86. }
  87. }
  88. }