我需要将 HTML5 canvas 输出作为视频或 swf png 序列。
我在 stackoverflow 上找到了以下用于捕获图像的链接。
Capture HTML Canvas as gif/jpg/png/pdf?
但是谁能建议我们是希望输出是视频还是 png 序列的 swf?
编辑:
好的,现在我明白了如何捕获 Canvas 数据以存储在服务器上,我试过了,如果我只使用形状、矩形或其他一些图形,它工作正常,但如果我在 Canvas 元素上绘制外部图像,则效果不佳。 谁能告诉我如何完全捕获 Canvas 数据,无论我们是使用图形还是外部图像在 Canvas 上绘图?
我使用了以下代码:
var cnv = document.getElementById("myCanvas");
var ctx = cnv.getContext("2d");
if(ctx)
{
var img = new Image();
ctx.fillStyle = "rgba(255,0,0,0.5)";
ctx.fillRect(0,0,300,300);
ctx.fill();
img.onload = function()
{
ctx.drawImage(img, 0,0);
}
img.src = "my external image path";
var data = cnv.toDataURL("image/png");
}
将 Canvas 数据放入我的“数据”变量后,我创建了一个新 Canvas 并在其上绘制捕获的数据,红色矩形绘制在第二个 Canvas 上,但外部图像没有。
提前致谢。
最佳答案
我建议:
使用
setInterval
将 Canvas 的内容捕获为 PNG 数据 URL。function PNGSequence( canvas ){ this.canvas = canvas; this.sequence = []; }; PNGSequence.prototype.capture = function( fps ){ var cap = this; this.sequence.length=0; this.timer = setInterval(function(){ cap.sequence.push( cap.canvas.toDataURL() ); },1000/fps); }; PNGSequence.prototype.stop = function(){ if (this.timer) clearInterval(this.timer); delete this.timer; return this.sequence; }; var myCanvas = document.getElementById('my-canvas-id'); var recorder = new PNGSequence( myCanvas ); recorder.capture(15); // Record 5 seconds setTimeout(function(){ var thePNGDataURLs = recorder.stop(); }, 5000 );
将所有这些 PNG 数据 URL 发送到您的服务器。这将是一大堆数据。
使用您喜欢的任何服务器端语言(PHP、Ruby、Python)从数据 URL 中去除 header ,这样您就只剩下 base64 编码的 PNG
使用您喜欢的任何服务器端语言,将 base64 数据转换为二进制并写出临时文件。
在服务器上使用您喜欢的任何第 3 方库,将 PNG 文件序列转换为视频。
编辑:关于您对外部图像的评论,您不能从不是origin-clean 的 Canvas 创建数据URL。 .只要您对外部图像使用 drawImage()
,您的 Canvas 就会被污染。从该链接:
All canvas elements must start with their origin-clean set to true. The flag must be set to false if any of the following actions occur:
[...]
The element's 2D context's
drawImage()
method is called with anHTMLImageElement
or anHTMLVideoElement
whose origin is not the same as that of the Document object that owns the canvas element.[...]
Whenever the
toDataURL()
method of a canvas element whose origin-clean flag is set to false is called, the method must raise aSECURITY_ERR
exception.Whenever the
getImageData()
method of the 2D context of a canvas element whose origin-clean flag is set to false is called with otherwise correct arguments, the method must raise aSECURITY_ERR
exception.
关于javascript - 将 html5 Canvas 输出捕获为视频或 swf 或 png 序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4781602/