通过 canvas.toDataURL 将画布保存到图像会导致黑色矩形

我正在使用 Pixi.js 并尝试将动画帧保存到图像中.canvas.toDataUrl 应该可以工作,但我得到的只是一个黑色矩形.查看现场示例这里

Im using Pixi.js and trying to save a frame of the animation to an image. canvas.toDataUrl should work, but all i get is a black rectangle. See live example here

我用来提取图像数据并设置图像的代码是:

the code I use to extract the image data and set the image is:

            var canvas = $('canvas')[0];
            var context = canvas.getContext('2d');

            $('button').click(function() {

                var data = renderer.view.toDataURL("image/png", 1);
                //tried var data = canvas.toDataURL();
                $('img').attr('src', data);
            })

推荐答案

[注意]

虽然这个答案是公认的答案,但请阅读下面@gman 的那个,它确实包含更好的方式.

[NOTE]

While this answer is the accepted one, please do read the one by @gman just below, it does contain a way better way of doing.

您的问题是您使用的是 webGL 上下文,那么您需要将 webGL 上下文的 preserveDrawingBuffer 属性设置为 true 以便能够调用 toDataURL() 方法.

Your problem is that you are using webGL context, then you need to set the preserveDrawingBuffer property of the webGL context to true in order to be able to call toDataURL() method.

或者,您可以强制 pixi 使用 2D 上下文,方法是使用 CanvasRenderer

Or alternatively, you can force pixi to use the 2D context, by using the CanvasRenderer Class

相关文章