how to function a gif image in javascript code example

Example: javascript create gif from images

You cannot create GIFs natively using canvas but you can use a libray called JSGif to do this:
https://github.com/antimatter15/jsgif

From the read me file:

Now we need to init the GIFEncoder.

var encoder = new GIFEncoder();
If you are making an animated gif, you need to add the following

encoder.setRepeat(0); //0  -> loop forever
                      //1+ -> loop n times then stop
encoder.setDelay(500); //go to next frame every n milliseconds
Now, you need to tell the magical thing that you're gonna start inserting frames (even if it's only one).

encoder.start();
And for the part that took the longest to port: adding a real frame.

encoder.addFrame(context);
For more details check out its documentation