我正在尝试将 mjpg 视频的实时流写入 html Canvas 。
以下内容:http://camelive.info/有一个带有 mjpeg 视频的公共(public)网络摄像头列表,但它们似乎正在编写带有框架元素的
最佳答案
根据to specs关于 CanvasRenderingContext2D drawImage
方法,
Specifically, when a CanvasImageSource object represents an animated image in an HTMLImageElement, the user agent must use the default image of the animation (the one that the format defines is to be used when animation is not supported or is disabled), or, if there is no such image, the first frame of the animation, when rendering the image for CanvasRenderingContext2D APIs.
这适用于.gif、SMIL 动画.svg 和.mjpeg 媒体。因此,一旦您获取了数据,就应该只在 Canvas 上绘制一帧。
注意 chrome has a bug并且只尊重 .gif 图片,但他们可能有一天会修复它。
您自己注意到的一个解决方案是使用清除缓存 hack ( 'your.url/?' + new Date().getTime();
) 获取另一个新帧,但是您将失去 mjpeg 格式(部分帧内容)的任何优势并且不能确定什么时候刷新。
因此,如果适用,更好的解决方案是使用视频格式。视频的每一帧都可以绘制到 Canvas 上。
编辑2018
第三个解决方案在两年后浮现在我的脑海中:
UA 不依赖于在内存中为文档中的所有 2DContexts 保留相同的默认图像。
虽然对于其他格式我们仍然有点卡住,但对于没有明确定义的默认图像 的 MJPEG 流,我们实际上落到了动画的第一帧。
所以通过绘制 <img>
在不同的时间在两个不同的 Canvas 上包含我们的 MJPEG 流,理论上我们可以在 Canvas 上绘制相同 MJPEG 流的两个不同帧。
这是仅在 Firefox 62 上测试的概念证明。
var ctx_stream = stream.getContext('2d');
var ctx_direct = direct.getContext('2d');
img.onload = function() {
stream.width = direct.width = this.naturalWidth;
stream.height = direct.height = this.naturalHeight;
// onload should fire multiple times
// but it seems it's not at every frames
// so we'll disable t and use an interval instead
this.onload = null;
setInterval(draw, 500);
};
function draw() {
// create a *new* 2DContext
var ctx_off = stream.cloneNode().getContext('2d');
ctx_off.drawImage(img, 0,0);
// and draw it back to our visible one
ctx_stream.drawImage(ctx_off.canvas, 0,0);
// draw the img directly on 'direct'
ctx_direct.drawImage(img, 0,0);
}
img.src = "http://webcam.st-malo.com/axis-cgi/mjpg/video.cgi?resolution=704x576&dummy=1491717369754";
canvas,img{
max-height: 75vh;
}
Using a new offcreen canvas every frame: <br><canvas id="stream"></canvas><br>
The original image: <br><img id="img"><br>
Drawing directly the <img> (if this works your browser doesn't follow the specs): <br><canvas id="direct"></canvas><br>
因此,虽然此解决方案显然会带来性能影响(我们正在创建一个全新的 Canvas 元素及其每一帧的 2DContext),但它仍然可能比泛洪网络更好。无论如何,所有这些都应该很容易被垃圾收集。
关于javascript - 将本地 mjpg 视频流式传输到 html Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36137686/