How to put a gif with Canvas

前端 未结 6 1329
孤街浪徒
孤街浪徒 2020-12-23 23:43

I\'m creating a game, and in my game, when the HERO stay near the MONSTER, a gif will be showed, to scare the player. But I have no idea how to do this. I tried to put PHP o

6条回答
  •  情话喂你
    2020-12-24 00:14

    You can use Gify & gifuct-js projects on Github.

    First, download your Animated gif and prepare the images you need to do this on page load.

    var framesArray;
    var currentFrame = 0;
    var totalFrames = null;
    
    var oReq = new XMLHttpRequest();
    oReq.open("GET", "/myfile.gif", true);
    oReq.responseType = "arraybuffer";
    
    oReq.onload = function (oEvent) {
      var arrayBuffer = oReq.response; // Note: not oReq.responseText
      if(gify.isAnimated(arrayBuffer)){
          var gif = new GIF(arrayBuffer);
          framesArray = gif.decompressFrames(true);
          totalFrames = framesArray.length;
      }
    };
    
    oReq.send(null);
    

    When you want your animation to show so in your draw loop

    if((xHero >= xMonster-10)&&(xHero <= xMonster + 10)){
        // you need to work out from your frame rate when you should increase current frame 
        // based on the framerate of the gif image using framesArray[currentFrame].delay
    
        // auto-detect if we need to jump to the first frame in the loop 
        // as we gone through all the frames
        currentFrame = currentFrame % totalFrames;
        var frame = framesArray[currentFrame];
        var x,y;
        // get x posstion as an offset from xHero
        // get y posstion as an offset from yHero
    
        objContexto.putImageData(frame.patch,x,y);
    }
    

    Please note this code is not tested I built following the documentation of the 2 projects so it might be a little wrong but it shows roughly how it is possible, the 3rd link is the online contents of the demo folder for the gitfuct-js library

    1. https://github.com/rfrench/gify
    2. https://github.com/matt-way/gifuct-js
    3. http://matt-way.github.io/gifuct-js/

提交回复
热议问题