how to save canvas data to file

后端 未结 2 1694
谎友^
谎友^ 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条回答
  •  长情又很酷
    2020-12-02 11:02

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

    HTML snippet that generates the sample image I used:

    
    
    

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

    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

提交回复
热议问题