javascript - 单个 Canvas Sprite 动画可以工作,但如果有两个 Canvas 则不行

标签 javascript jquery html canvas

使用canvas元素处理一些动画 Sprite 。

我已经成功地设置了一个运行良好的测试用例,但仅使用一个 Canvas 元素,最终就会有任意给定数量的动画 Sprite 。

不明白为什么?

<强> Working demo.
<强> Broken demo.

  <canvas id="video1"></canvas>
  <input type="button" onclick="PS.draw(1)" value="Play">
  <input type="button" onclick="PS.stop(1)" value="Stop">

  <canvas id="video2"></canvas>
  <input type="button" onclick="PS.draw(2)" value="Play">
  <input type="button" onclick="PS.stop(2)" value="Stop">

  <script>
  var PS = {

    init: function(id) { // setup the premise for the canvases, this data is needed to animate the sprites.
      var sprites = [];
      var context = document.getElementById(src.entries[id].file.ios.filename);
      $(context).attr('width', src.entries[id].file.ios.width);
      $(context).attr('height', src.entries[id].file.ios.height);
      context = context.getContext('2d');

      var array = src.entries[id].file.ios.sprite;
      for (var i = 0; i < array.length; i++) {
        sprites[i] = new Sprite(array[i], { frameW: src.entries[id].file.ios.width, frameH: src.entries[id].file.ios.height, interval: src.entries[id].file.ios.framerate, useTimer: false }); // sprite.js, associates each sprite with given settings.
      }

      var activeSprite = sprites[0];
      var framesDrawn = 0;
      var f = 0;
      var sprite = 0;

      //var filename = src.entries[id].file.ios.filename
      window['sprite' + id] = {
        "context" : context, 
        "activeSprite" : activeSprite, 
        "framesDrawn" : framesDrawn, 
        "f" : f,
        "sprites" : sprites, 
        "sprite" : sprite, 
        "framerate" : src.entries[id].file.ios.framerate, 
        "frames" : src.entries[id].file.ios.frames,
      };
    },

    /*
      ^ How do I pass this on to draw()? Global vars?
    */

    draw: function(id) {
      //var filename = src.entries[id].file.ios.filename;
      //console.log(window.filename.context);
      //console.log(window.sprite+id);

      window['sprite' + id ].player = setTimeout(function() { // I'm here to throttle to approriate framerate
        requestAnimationFrame(function() {
          PS.draw(id);
        });

        window['sprite' + id ].framesDrawn++;
        window['sprite' + id ].f++;
        window['sprite' + id ].activeSprite.draw(window['sprite' + id ].context, 0, 0);

        if(window['sprite' + id ].f == window['sprite' + id ].frames) { // you've reached the total frames of animation, reset to first spritesheet
          window['sprite' + id ].sprite = 0;
          window['sprite' + id ].activeSprite = window['sprite' + id ].sprites[window['sprite' + id ].sprite];
          window['sprite' + id ].framesDrawn = 0;
          window['sprite' + id ].f = 0;     
        }

        if(window['sprite' + id ].framesDrawn == 50) { // each sprite contains 50 images, thus change to new spritesheet
          window['sprite' + id ].sprite++;
          window['sprite' + id ].activeSprite = window['sprite' + id ].sprites[window['sprite' + id ].sprite];
          window['sprite' + id ].framesDrawn = 0;
        }

      }, 1000 / window['sprite' + id ].framerate);
    },

    stop: function(id) {
      //var filename = src.entries[id].file.ios.filename;
      clearTimeout(window['sprite' + id ].player); // some other better way?
    }
  }

  var src ={
    "entries":{
      "1":{
        "file":{
          "ios":{
            "filename":"video1",
            "sprite":["https:\/\/dl.dropboxusercontent.com\/u\/3618143\/sprite1.jpg","https:\/\/dl.dropboxusercontent.com\/u\/3618143\/sprite2.jpg","https:\/\/dl.dropboxusercontent.com\/u\/3618143\/sprite3.jpg"],
            "frames":"115",
            "framerate":"23.976",
            "width":"426",
            "height":"240"
          }
        }
      },
      "2":{
        "file":{
          "ios":{
            "filename":"video2",
            "sprite":["https:\/\/dl.dropboxusercontent.com\/u\/3618143\/sprite1.jpg","https:\/\/dl.dropboxusercontent.com\/u\/3618143\/sprite2.jpg","https:\/\/dl.dropboxusercontent.com\/u\/3618143\/sprite3.jpg"],
            "frames":"115",
            "framerate":"23.976",
            "width":"426",
            "height":"240"
          }
        }
      },
    }
  }

  setTimeout(function() {
    PS.init(1);
    PS.init(2);
  },500)  
  </script>

最佳答案

我无法弄清楚具体原因,但问题在于 sprite.js 使用图像缓存和预加载来初始化 Sprite 的方式。由于两个 canvas 元素显示同一组图像,因此在初始化第二个 Canvas 时它们会相互冲突,因此它会以某种方式损坏。

最简单的解决方案似乎是禁用 Sprite 图像缓存:

// override Sprite caching to prevent images conflicting
Sprite.getImageFromCache = function(src) {
    //return images[src] ? images[src] : null;
    return null;
};

Sprite.saveImageToCache = function(src, image) {
    //images[src] = image;
};

这是一个更新的 fiddle ,显示它的工作原理。 http://jsfiddle.net/xbcw7sbb/4/

请注意,我还重命名了一些变量,以便更容易理解它是什么,并将 filename 作为 data() 对象附加到 Canvas 中将所有内容放在一起。

此外,单击Play两次会导致动画循环在 Canvas 中运行两次,因此出现问题,因此我创建了一个 start(id) 方法,该方法仅调用draw() 如果它没有运行。 draw() 本身只需要上下文(您的 filename 对象),因此您可以每次传递它,这样您就不必从每次的其他位置检索它循环。

/* override Sprite caching to prevent images conflicting */
// (original code commented)

Sprite.getImageFromCache = function(src) {
    //return images[src] ? images[src] : null;
    return null;
};

Sprite.saveImageToCache = function(src, image) {
    //images[src] = image;
};


var PS = {

    init: function (id) {
        // setup the premise for the canvases,
        // this data is needed to animate the sprites.
        var sprites = [];
        var ios = src.entries[id].file.ios;
        var canvas = document.getElementById(ios.filename);
        $(canvas).attr('width', ios.width);
        $(canvas).attr('height', ios.height);
        var context = canvas.getContext('2d');

        var imgList = ios.sprite;
        for (var i = 0; i < imgList.length; i++) {
            sprites[i] = new Sprite(imgList[i], {
                frameW: ios.width,
                frameH: ios.height,
                interval: ios.framerate,
                useTimer: false
            }); // sprite.js, associates each sprite with given settings.
        }

        // attach the context to the canvas so we can retrieve it again
        $(canvas).data('spritecontext', {
            "context": context,
                "activeSprite": sprites[0],
                "framesDrawn": 0,
                "f": 0,
                "sprites": sprites,
                "sprite": 0,
                "framerate": ios.framerate,
                "frames": ios.frames
        });
    },

    start: function(id) {
        var canvasId = src.entries[id].file.ios.filename;
        var canvas = $('#' + canvasId);
        var spritecontext = canvas.data('spritecontext');
        if(!spritecontext.player) {
            PS.draw(id, spritecontext);
        }
    },

    draw: function (id, spritecontext) {
        spritecontext.player = setTimeout(function () {
            // I'm here to throttle to approriate framerate
            requestAnimationFrame(function () {
                PS.draw(id, spritecontext);
            });

            spritecontext.framesDrawn++;
            spritecontext.f++;
            spritecontext.activeSprite.draw(spritecontext.context, 0, 0);

            if (spritecontext.f == spritecontext.frames) {
                // you've reached the total frames of animation,
                // reset to first spritesheet
                spritecontext.sprite = 0;
                spritecontext.activeSprite = spritecontext.sprites[spritecontext.sprite];
                spritecontext.framesDrawn = 0;
                spritecontext.f = 0;
            }

            if (spritecontext.framesDrawn == 50) {
                // each sprite contains 50 images, thus change to new spritesheet
                spritecontext.sprite++;
                spritecontext.activeSprite = spritecontext.sprites[spritecontext.sprite];
                spritecontext.framesDrawn = 0;
            }

        }, 1000 / 23.976);
    },

    stop: function (id) {
        var canvasId = src.entries[id].file.ios.filename;
        var canvas = $('#' + canvasId);
        var spritecontext = canvas.data('spritecontext');
        // some other better way? - probably not
        clearTimeout(spritecontext.player);
        // so we know its stopped
        spritecontext.player = null;
    }
}

var src = {
    "entries": {
        "1": {
            "file": {
                "ios": {
                    "filename": "video1",
                        "sprite":
    ["https:\/\/dl.dropboxusercontent.com\/u\/3618143\/sprite1.jpg",
     "https:\/\/dl.dropboxusercontent.com\/u\/3618143\/sprite2.jpg",
     "https:\/\/dl.dropboxusercontent.com\/u\/3618143\/sprite3.jpg"],
                        "frames": "115",
                        "framerate": "23.976",
                        "width": "426",
                        "height": "240"
                }
            }
        },
        "2": {
            "file": {
                "ios": {
                    "filename": "video2",
                    "sprite": 
    ["https:\/\/dl.dropboxusercontent.com\/u\/3618143\/sprite1.jpg",
     "https:\/\/dl.dropboxusercontent.com\/u\/3618143\/sprite2.jpg",
     "https:\/\/dl.dropboxusercontent.com\/u\/3618143\/sprite3.jpg"],
                        "frames": "115",
                        "framerate": "23.976",
                        "width": "426",
                        "height": "240"
                }
            }
        },
    }
}

setTimeout(function () {
    PS.init(1);
    PS.init(2);
}, 500);

关于javascript - 单个 Canvas Sprite 动画可以工作,但如果有两个 Canvas 则不行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26045680/

相关文章:

ajax - 带有 Video.js 和 AJAX 的 HTML5 视频

html - 垂直填充,但根据内容保持宽度

html - 在图像下方显示下拉值

javascript - 检查用户是否正在访问纯根 url

javascript - 无法将表单提交到 PHP 脚本

javascript - 将 SVG 对象存储在数组中以供加载

javascript - jquery 同时淡入淡出

jquery 功能和文档就绪

javascript - 未在下拉菜单中选择元素

javascript - 如何播放 RAW 音频文件?