Skip to content

Instantly share code, notes, and snippets.

@srestraj
Last active October 8, 2023 05:39
Show Gist options
  • Save srestraj/97539a0af93552ff06866f5df48cd771 to your computer and use it in GitHub Desktop.
Save srestraj/97539a0af93552ff06866f5df48cd771 to your computer and use it in GitHub Desktop.
Extract video frame from a file input using JS and Canvas
Create an input element to let users upload a video
<label for="file">Upload Video</label> 
<input type="file" accept=".mp4, .mkv, .mpeg4" id="file" class="video-input">
<button class="capture-btn">Capture</button>
<div class="source-vid"></div>
<div class="result"></div>
JS
const btn = document.querySelector(".capture-btn");
const inputEl = document.querySelector(".video-input");
const vidEl = document.querySelector(".source-vid");
const resultEl = document.querySelector(".result");

inputEl.addEventListener("change", (e) => {
  vidEl.innerHTML = `<video autoplay controls muted loop style="width: 100%"><source src="${URL.createObjectURL(
    e.target.files[0]
  )}" type="${e.target.files[0].type}"></source></video>`;
});

btn.addEventListener("click", () => {
  const video = document.querySelector("video");
  if (video) {
    const canvas = document.createElement("canvas");
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    canvas
      .getContext("2d")
      .drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
    const generatedImage = canvas.toDataURL("image/png");
    resultEl.innerHTML = `<img src="${generatedImage}" style="width: 100%" />`;
  }
});

Live demo here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment