通过 canvas.toDataURL 将画布保存为图像会产生黑色矩形 [英] Saving canvas to image via canvas.toDataURL results in black rectangle

查看:39
本文介绍了通过 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);
            })

推荐答案

[NOTE]

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

[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

这篇关于通过 canvas.toDataURL 将画布保存为图像会产生黑色矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆