How To Play GIF In Angular

Introduction:

Canvas can’t generate (animated) GIFs. You need to use a JavaScript library to do so.

Here we use npm for GIF.

For forward-backward animations, duplicate frames added using gif.addFrame() will only be processed once.

To save memory and increase performance, images created by web workers were transmitted back.

JavaScript GIF encoder that runs in your browser. Each frame is rendered quickly in the background using typed arrays and web workers!

Let’s start…

Step : 1 Create New Project 

Write the command below in the terminal.

ng new canvas-gif

Step : 2 Install gif package

Now, we need to install npm by writing the following command into the terminal.

npm i gif.js.optimized

Step 3: ADD gif file

download the gif file and add it to asset folder or anywhere in the project folder.

Step: 4 Update HTML file

copy the code & paste it into in app.component.html file.

<p>
  Start editing to see some magic happen :)
</p>
<img #img src="/assets/ZKZg.gif" alt="">
<canvas #canvas width="600" height="300"></canvas>

Step : 5 Update app.component.ts file

import { Component, ElementRef, ViewChild } from '@angular/core';
const gif = require('gif.js.optimized');


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
  @ViewChild('img', { static: true }) img?: ElementRef;
  @ViewChild('canvas', { static: true }) canvas?: ElementRef;
  gif: any;

  
  ngOnInit() {
   this.gif = new gif.default({
        workers: 2,
        quality: 10
      });
      // add an image element
      this.gif.addFrame(this.img);
  
      this.gif.on('finished', function (blob:any) {
        window.open(URL.createObjectURL(blob));
      });
  
      this.gif.render();
}
}

There are  some options in the gif constructor as follows:

repeat: repeat count,

-1 = no repeat,

0 = forever

quality: pixel sample interval, lower is better

background: background color where the source image is transparent

workers: number of web workers to spawn

transparent: transparent hex color, 0x00FF00= green

you can also add options in addFrame.

delay: it defines delay in the frame. The default value is 500

copy: copy the pixel data. The default value is false.

OUTPUT : 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories