Krishnab Sarkar
Krishnab Sarkar

Reputation: 1

Change filename according to fps using js

Suppose I have 500 images named 0001.jpeg to 0500.jpeg. I want those images to change so fast such that the changing of the images appears as a video. The images to be changed per second is 25.

<img src="0001.jpeg">

So I need this src to be changed 25 times every second and the file name should be changed automatically using increment. Please use vanilla js. Thanks in advance!!!

Upvotes: 0

Views: 78

Answers (2)

Reyno
Reyno

Reputation: 6505

You can use setInterval to create a loop with a specific FPS. Each iteration you can update the src of the image. By adding in the remainder operator (%) we can keep the "video" looping.

The addition of requestAnimationFrame makes sure there is time to paint the new image on the screen.

Be aware that if the images are too big there will be no time to show them properly.

const FPS = 25;
const TOTAL_IMAGES = 500;

let index = 1;
const img = document.querySelector("img");

const pad = (num) => num.toString().padStart(4, "0");

const intervalID = setInterval(() => {
  index = (index + 1) % TOTAL_IMAGES;
  const src = `${pad(index)}.jpeg`;
  
  requestAnimationFrame(() => img.setAttribute("src", src));
  
  console.log(src);
}, 1000 / FPS);

// To stop the loop you can call `clearInterval(intervalID)`
<img src="0001.jpeg">

EDIT: Explantion of pad function

The line const pad = (num) => num.toString().padStart(4, "0"); just makes sure the image name is always in the following format: "0000".

Steps taken inside the function

  1. Pass down a number (num variable)
  2. Turn the number into a string (via toString method, we do this because we can only use padStart on strings)
  3. Turn the number into the right length (padStart takes two arguments. First the length we want the result to be, in our case the number must be four characters long. The second argument is what we add to the beginning of the string until it reaches the desired length)
  4. Return the result.

TLDR:

So let's say we pass down 5 we turn it into a string ("5"). Then we apply the padding ("0005"). Finally we return it back to the src variable inside the interval function ("0005.jpeg").

Upvotes: 1

anpel
anpel

Reputation: 941

HTML:

<img id="foo" src="0001.jpeg">

Javascript:

var el = document.getElementById('foo');
var src = 1;
var intervalID = window.setInterval(changeSource, 40);

function changeSource()
{
    var current = src++;
    el.src = String("0000" + current).slice(-4) + '.jpeg';
}

Upvotes: 0

Related Questions