Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

javascript - how to save canvas data to file

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 = 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.'
        });
    }
 });    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

<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:

const fs = require("fs").promises;

(async () => {
  
  // string generated by canvas.toDataURL()
  const img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0"
      + "NAAAAKElEQVQ4jWNgYGD4Twzu6FhFFGYYNXDUwGFpIAk2E4dHDRw1cDgaCAASFOffhEIO"
      + "3gAAAABJRU5ErkJggg==";
  
  // strip off the data: url prefix to get just the base64-encoded bytes
  const data = img.replace(/^data:image/w+;base64,/, "");
  
  const buf = Buffer.from(data, "base64");
  await fs.writeFile("image.png", buf);
})();

Output:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...