A
A
Alex2021-07-07 10:02:36
JavaScript
Alex, 2021-07-07 10:02:36

How to get a frame from a video as a picture in WebWorker?

There is a video, represented by a link to an mp4 file. I want to get frames from a video for certain timecodes (to show a preview when hovering over the timeline ). There is no backend that could do this. All videos are loaded from a third-party server.

At the moment, the preview is generated like this:

const video = document.createElement('video') // Создаём новый тег video
video.preload = 'metadata' // Заставляем браузер загружать метаданные 
video.src = TARGET_SOURCE_URL // указываем ссылку на нужный источник
video.currentTime = TARGET_TIMECODE // перематываем видео на нужный кадр

const canvas = document.createElement('canvas')  // создаём canvas для отрисовки кадра
const ctx = canvas.getContext('2d')
ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight) // рисуем загруженный кадр видео на canvas 
canvas.toDataURL() // Получаем кадр в виде data URL


The problem is that all this happens in the main thread, and there are a lot of frames to draw. And users may experience that the application slows down until all the frames are loaded.

Is it possible to somehow implement all the same, but inside the WebWorker? I know that OffscreenCanvas can be used inside the worker, but how do I load a video frame to draw it? The main thread uses the DOM API for this, which is not available in the worker.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question