how to save canvas data to file

后端 未结 2 1685
谎友^
谎友^ 2020-12-02 10:35

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

var fs          


        
2条回答
  •  萌比男神i
    2020-12-02 11:06

    I believe that Canvas does 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.

    Quick googling to node canvas documentation gives:

    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.

    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).

提交回复
热议问题