Javascript 如何将画布数据保存到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5867534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:16:23  来源:igfitidea点击:

how to save canvas data to file

javascripthtmlnode.js

提问by sw-dev

i am using node.js to save canvas to image img in writeFile is extractedby using toDataURL on my canvas element. it doenot save file here is my code

我正在使用 node.js 将画布保存到 writeFile 中的图像 img 是通过在我的画布元素上使用 toDataURL 来提取的。它不保存文件这里是我的代码

var fs = IMPORTS.require('fs');
var path = IMPORTS.require('path');
path.exists('images/', function(exists){
    if (exists) {

        fs.writeFile('images/icon.png', img, function(err){
            if (err) 
                callback({
                    error: false,
                    reply: err
                });
            console.log('Resized and saved in');
            callback({
                error: false,
                reply: 'success.'
            });
        });
    }
    else {
        callback({
            error: true,
            reply: 'File did not exist.'
        });
    }
 });    

回答by samplebias

Here is a literal example of how to save canvas data to a filein Nodejs. The variable imgis a string generated by canvas.toDataURL(). I've assumed you already know how to POST that string from the browser to your Nodejs server.

这是一个如何在 Nodejs 中将画布数据保存到文件的文字示例。变量img是一个由 生成的字符串canvas.toDataURL()。我假设您已经知道如何将该字符串从浏览器 POST 到您的 Nodejs 服务器。

HTML snippet that generates the sample image I used:

生成我使用的示例图像的 HTML 片段:

<canvas id="foo" width="20px" height="20px"></canvas>
<script>
var ctx = $('#foo')[0].getContext('2d');
for (var x = 0; x < 20; x += 10) {
    for (var y = 0; y < 20; y += 10) {
        if (x == y) { ctx.fillStyle = '#000000'; }
        else { ctx.fillStyle = '#8888aa'; }
        ctx.fillRect(x, y, 10, 10);
    }
}
console.log($('#foo')[0].toDataURL());
</script>

Nodejs snippet to decode the base64 data and save the image:

用于解码 base64 数据并保存图像的 Nodejs 片段:

fs = require('fs');
sys = require('sys');
// string generated by canvas.toDataURL()
var img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0"
    + "NAAAAKElEQVQ4jWNgYGD4Twzu6FhFFGYYNXDUwGFpIAk2E4dHDRw1cDgaCAASFOffhEIO"
    + "3gAAAABJRU5ErkJggg==";
// strip off the data: url prefix to get just the base64-encoded bytes
var data = img.replace(/^data:image\/\w+;base64,/, "");
var buf = new Buffer(data, 'base64');
fs.writeFile('image.png', buf);

Output:

输出:

enter image description here

在此处输入图片说明

回答by Dan

I believe that Canvasdoes not store it's data in Base64 internally. It should store data in some much more efficient binary format. So, obviously, transferring to base64 and back to binary PNG is terribly slow and memory consuming.

我相信它Canvas不会在内部将其数据存储在 Base64 中。它应该以更高效的二进制格式存储数据。因此,显然,传输到 base64 并返回到二进制 PNG 非常慢且占用内存。

Quick googling to node canvas documentationgives:

快速谷歌搜索节点画布文档提供:

To create a PNGStream simply call canvas.pngStream(), and the stream will start to emit data events, finally emitting end when finished. If an exception occurs the error event is emitted.

要创建 PNGStream,只需调用 canvas.pngStream(),流将开始发出数据事件,最后在完成时发出结束。如果发生异常,则发出错误事件。

var fs = require('fs')
  , out = fs.createWriteStream(__dirname + '/text.png')
  , stream = canvas.pngStream();

stream.on('data', function(chunk){
  out.write(chunk);
});

stream.on('end', function(){
  console.log('saved png');
});

Currently only sync streaming is supported. If you want to do it async, you can try to use a worker or cluster (I personally never tried this).

目前仅支持同步流。如果你想做异步,你可以尝试使用一个工作程序或集群(我个人从未尝试过)。