如何解决createElement在Web Worker中为只读
我知道从Web Worker访问DOM对于线程安全是一个坏主意,但我认为在我的用例中,它应该是绝对安全的。
我正在尝试在特定时间段(对于我的用例,一遍又一遍)从视频中获取图像数据。因为这是一个繁重而不关键的过程,所以在工作线程中执行此操作将是理想的选择。这是我想在工作线程中运行的(剥离版本)代码:
const video = document.createElement('video')
video.src = 'My video src'
video.currentTime = desiredTimestamp
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
context.drawImage(video,w,h) //paints data onto a canvas
return canvas.toDataURL() //takes data and makes it a string
在工作进程中运行时,JS会引发错误,指出文档未定义。有什么方法可以不必在主线程中执行此操作吗?如果这不是适合工人的用例,那么还有其他方法可以在“后台”执行此操作吗?我希望所有其他进程对此具有优先权。
解决方法
很遗憾,在Worker上下文中仍然无法从视频中获取帧。
也许Web-Codecs API会提供这一点,但无论如何都是为了将来。
当前,您能做的最好的就是从视频中创建一个ImageBitmap,并将其传递给Worker中的OffscreenCanvas,在其中它可以继续在其他线程中处理静止图像。
但是,由于仅生成这些静止图像,因此Web-Worker并没有太大帮助,因为抓取视频帧的最大工作已经完成,并且除非绘制了非常大的视频帧,否则整个过程都不应此外,如果仅使用异步API,也不会对页面造成太多阻碍。
这是一段注释过的代码,我认为它提供了从视频中获取静止图像的最不优先的方式。
async function getFrame( url,time ) {
const video = document.createElement('video');
video.crossOrigin = 'anonymous';
// Fetching and seeking are done in parallel,should not block the main thread
video.src = url;
video.currentTime = time;
await new Promise( res => { video.onseeked = res; } );
// createImageBitmap is truly async only with Blobs
// so if you really want to be sure it doesn't interfere with other running scripts
// you can wait for the next idle
await new Promise( res => requestIdleCallback( res ) );
const img = await createImageBitmap( video );
// This can be done synchronously,very small computation required
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const context = canvas.getContext('bitmaprenderer')
context.transferFromImageBitmap( img );
// You probably don't need a data:// URL so instead we'll generate a blob:// URL
// Even though the copy of pixels is still done synchronously
// the compression is most likely done in parallel
const blob = await new Promise( res => canvas.toBlob( res ) )
return URL.createObjectURL( blob );
}
getFrame( 'https://upload.wikimedia.org/wikipedia/commons/a/a4/BBH_gravitational_lensing_of_gw150914.webm',2 ).then( url => {
const img = new Image();
document.body.append( img );
img.src = url;
} )
.catch( console.error );
,
答案是后台任务API,可在以下位置找到:https://developer.mozilla.org/en-US/docs/Web/API/Background_Tasks_API我宁愿在后台线程上进行此加载,因此请不要使用,但这是我将使用的,除非出现更好的情况。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。