Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

javascript - How to put a gif with Canvas

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 or HTML code, but it doesn't works... The function is AtualizaTela2(). This is my main code:

<!DOCTYPE HTML>
<html>
<head>
<title>Hero's Escape Game</title>
<script language="JavaScript" type="text/javascript">

var objCanvas=null; // object that represents the canvas
var objContexto=null; 

// Hero positioning control
var xHero=300;
var yHero=100;

// Monster positioning control
var xMonster=620;
var yMonster=0;

var imgFundo2 = new Image();
imgFundo2.src = "Images/Pista2.png";

var imgMonster = new Image();
imgMonster.src = "Images/Monster.png";

var imgHero = new Image();
imgHero.src = "Images/Hero.png";

function AtualizaTela2(){

if((xHero >= xMonster-10)&&(xHero <= xMonster + 10))
{

/*gif here*/

}

objContexto.drawImage(imgFundo2,0,0);
objContexto.drawImage(imgHero, xHero, yHero);
objContexto.drawImage(imgMonster, xMonster, yMonster);

function Iniciar(){

objCanvas = document.getElementById("meuCanvas");
objContexto = objCanvas.getContext("2d");
AtualizaTela2();

}

/* the function HeroMovement() and MonsterMovement() are not here */

}

</script>
</head>
<body onLoad="Iniciar();" onkeydown="HeroMovement(event);">

<canvas id="meuCanvas" width="1233"
height="507"
style="border:1px solid #000000;">
Seu browser n?o suporta o elemento CANVAS, atualize-se!!!
</canvas><BR>
</body>
</html>

This is the simplified code, because the real code is very big!

Thanks for the help! :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Loading and playing GIF image to canvas.

Sorry answer exceeded size limit, had to remove much of the detailed code comments.

I am not going to go into details as the whole process is rather complicated.

The only way to get a GIF animated in canvas is to decode the GIF image in javascript. Luckily the format is not too complicated with data arranged in blocks that contain image size, color pallets, timing information, a comment field, and how frames are drawn.

Custom GIF load and player.

The example below contains an object called GIF that will create custom format GIF images from URLs that can play a GIF similar to how a video is played. You can also randomly access all GIF frames in any order.

There are many callbacks and options. There is basic usage information in comments and the code shows how to load the gif. There are functions to pause and play, seek(timeInSeconds) and seekFrame(frameNumber), properties to control playSpeed and much more. There are no shuttling events as access is immediate.

 var myGif = GIF();
 myGif.load("GIFurl.gif");

Once loaded

 ctx.drawImage(myGif.image,0,0); // will draw the playing gif image

Or access the frames via the frames buffer

 ctx.drawImage(myGif.frames[0].image,0,0); // draw frame 0 only.

Go to the bottom of the GIF object to see all the options with comments.

The GIF must be same domain or have CORS header

The gif in he demo is from wiki commons and contains 250+ frames, some low end devices will have trouble with this as each frame is converted to a full RGBA image making the loaded GIF significantly larger than the gif file size.

The demo

Loads the gif displaying the frames and frame count as loaded. When loaded 100 particles each with random access frames playing at independent speeds and independent directions are displayed in the background.

The foreground image is the gif playing at the frame rate embedded in the file.

Code is as is, as an example only and NOT for commercial use.

const ctx = canvas.getContext("2d");

var myGif;
// Can not load gif cross domain unless it has CORS header
const gifURL = "https://upload.wikimedia.org/wikipedia/commons/a/a2/Wax_fire.gif";
// timeout just waits till script has been parsed and executed
// then starts loading a gif
setTimeout(()=>{
    myGif = GIF();                  // creates a new gif  
    myGif.onerror = function(e){
       console.log("Gif loading error " + e.type);
    }
    myGif.load(gifURL);  

},0); 
// Function draws an image
function drawImage(image,x,y,scale,rot){
    ctx.setTransform(scale,0,0,scale,x,y);
    ctx.rotate(rot);
    ctx.drawImage(image,-image.width / 2, -image.height / 2);
}
// helper functions
const rand  = (min = 1, max = min + (min = 0)) => Math.random() * (max - min) + min;
const setOf     =(c,C)=>{var a=[],i=0;while(i<c){a.push(C(i++))}return a};
const eachOf    =(a,C)=>{var i=0;const l=a.length;while(i<l && C(a[i],i++,l)!==true);return i};
const mod = (v,m) => ((v % m) + m) % m;

// create 100 particles
const particles = setOf(100,() => {
    return {
      x : rand(innerWidth),
      y : rand(innerHeight),
      scale : rand(0.15, 0.5),
      rot : rand(Math.PI * 2),
      frame : 0,
      frameRate : rand(-2,2),
      dr : rand(-0.1,0.1),
      dx : rand(-4,4),
      dy : rand(-4,4),
   };
});
// Animate and draw 100 particles
function drawParticles(){
  eachOf(particles, part => {
     part.x += part.dx;
     part.y += part.dy;
     part.rot += part.dr;
     part.frame += part.frameRate;
     part.x = mod(part.x,innerWidth);
     part.y = mod(part.y,innerHeight);
     var frame = mod(part.frame ,myGif.frames.length) | 0;
 
     drawImage(myGif.frames[frame].image,part.x,part.y,part.scale,part.rot);
  });
}      


var w = canvas.width;
var h = canvas.height;
var cw = w / 2; // center 
var ch = h / 2;

// main update function
function update(timer) {
  ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
  if (w !== innerWidth || h !== innerHeight) {
    cw = (w = canvas.width = innerWidth) / 2;
    ch = (h = canvas.height = innerHeight) / 2;
  } else {
    ctx.clearRect(0, 0, w, h);
  }
  if(myGif) { // If gif object defined
    if(!myGif.loading){  // if loaded
        // draw random access to gif frames
        drawParticles();
        drawImage(myGif.image,cw,ch,1,0); // displays the current frame.
    }else if(myGif.lastFrame !== null){  // Shows frames as they load
        ctx.drawImage(myGif.lastFrame.image,0,0); 
        ctx.fillStyle = "white";
        ctx.fillText("GIF loading frame " + myGif.frames.length ,10,21);
        ctx.fillText("GIF loading frame " + myGif.frames.length,10,19);
        ctx.fillText("GIF loading frame " + myGif.frames.length,9,20);
        ctx.fillText("GIF loading frame " + myGif.frames.length,11,20);
        ctx.fillStyle = "black";
        ctx.fillText("GIF loading frame " + myGif.frames.length,10,20);
        
    }
  
  }else{
        ctx.fillText("Waiting for GIF image ",10,20);
  
  }
  requestAnimationFrame(update);
}
requestAnimationFrame(update);

/*============================================================================
  Gif Decoder and player for use with Canvas API's

**NOT** for commercial use.

To use

    var myGif = GIF();                  // creates a new gif  
    var myGif = new GIF();              // will work as well but not needed as GIF() returns the correct reference already.    
    myGif.load("myGif.gif");            // set URL and load
    myGif.onload = function(event){     // fires when loading is complete
                                        //event.type   = "load"
                                        //event.path   array containing a reference to the gif
    }
    myGif.onprogress = function(event){ // Note this function is not bound to myGif
                                        //event.bytesRead    bytes decoded
                                        //event.totalBytes   total bytes
                                        //event.frame        index of last frame decoded
    }
    myGif.onerror = function(event){    // fires if there is a problem loading. this = myGif
                                        //event.type   a description of the error
                                        //event.path   array containing a reference to the gif
    }

Once loaded the gif can be displayed
    if(!myGif.loading){
        ctx.drawImage(myGif.image,0,0); 
    }
You can display the last frame loaded during loading

    if(myGif.lastFrame !== null){
        ctx.drawImage(myGif.lastFrame.image,0,0); 
    }


To access all the frames
    var gifFrames = myGif.frames; // an array of frames.

A frame holds various frame associated items.
    myGif.frame[0].image; // the first frames image
    myGif.frame[0].delay; // time in milliseconds frame is displayed for




Gifs use various methods to reduce the file size. The loaded frames do not maintain the optimisations and hold the full resolution frames as DOM images. This mean the memory footprint of a decode gif will be many time larger than the Gif file.
 */
const GIF = function () {
    // **NOT** for commercial use.
    var timerID;                          // timer handle for set time out usage
    var st;                               // holds the stream object when loading.
    var interlaceOffsets  = [0, 4, 2, 1]; // used in de-interlacing.
    var interlaceSteps    = [8, 8, 4, 2];
    var interlacedBufSize;  // this holds a buffer to de interlace. Created on the first frame and when size changed
    var deinterlaceBuf;
    var pixelBufSize;    // this holds a buffer for pixels. Created on the first frame and when size changed
    var pixelBuf;
    const GIF_FILE = { // gif file data headers
        GCExt   : 0xF9,
        COMMENT : 0xFE,
        APPExt  : 0xFF,
        UNKNOWN : 0x01, // not sure what this is but need to skip it in parser
        IMAGE   : 0x2C,
        EOF     : 59,   // This is entered as decimal
        EXT     : 0x21,
    };      
    // simple buffered stream used to read from the file 
    var Stream = function (data) { 
        this.data = new Uint8ClampedArray(data);
        this.pos  = 0;
        var len   = this.data.length;
        this.getString = function (count) { // returns a string from current pos of len count
            var s = "";
            while (count--) { s += String.fromCharCode(this.data[this.pos++]) }
            return s;
        };
        this.readSubBlocks = function () { // reads a set of blocks as a string
            var size, count, data  = "";
            do {
                count = size = this.data[this.pos++];
                while (count--) { data += String.fromCharCode(this.data[this.pos++]) }
            } while (size !== 0 && this.pos < len);
            return data;
        }
        this.readSubBlocksB = function () { // reads a set of blocks as binary
            var size, count, data = [];
            do {
                count = size = this.data[this.pos++];
                while (count--) { data.push(this.data[this.pos++]);}
            } while (size !== 0 && this.pos < len);
            return data;
        }
    };
    // LZW decoder uncompressed each frames pixels
    // this needs to be optimised.
    // minSize is the min dictionary as powers of two
    // size and data is the compressed pixels
    function lzwDecode(minSize, data) {
        var i, pixelPos, pos, clear, eod, size, done, dic, code, last, d, len;
        pos = pixelPos = 0;
        dic      = [];
        clear    = 1 << minSize;
        eod      = clear + 1;
        size     = minSize + 1;
        done     = false;
        while (!done) { // JavaScript optimisers like a clear exit though I never use 'done' apart from fooling the optimiser
            last = code;
            code = 0;
            for (i = 0; i < size; i++) {
                if (data[pos >> 3] & (1 << (pos & 7))) { code |= 1 << i }
                pos++;
            }
            if (code === clear) { // clear and reset the dictionary
                dic = [];
                size = minSize + 1;
                for (i = 0; i < clear; i++) { dic[i] = [i] }
                dic[clear] = [];
                dic[eod] = null;
            } else {
                if (code === eod) {  done = true; return }
                if (code >= dic.length) { dic.push(dic[last].concat(dic[last][0])) }
                else if (last !== clear) { dic.push(dic[last].concat(dic[code][0])) }
                d = dic[code];
                len = d.length;
                for (i = 0; i < len; i++) { pixelBuf[pixelPos++] = d[i] }
                if (dic.length === (1 << size) && size < 12) { size++ }
            }
        }
    };
    function parseColourTable(count) { // get a colour table of length count  Each entry is 3 bytes, for RGB.
        var colours = [];
        for (var i = 0; i < count; i++) { colours.push([st.data[st.pos++], st.data[st.pos++], st.data[st.pos++]]) }
        return colours;
    }
    function parse (){        // read the header. This is the starting point of the decode and asy

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...