从我在评论中给出的主题来看,它给出了奇怪的结果。
由于我不知道您是否坚持将按钮设为 <button> 而不是 <a>,因此我创建了一个解决方法以使其看起来有效。
编辑:
如果要将图像保存到服务器。
改变
// Create a hidden link to do the download trick.
var a =document.createElement("a");
a.setAttribute("href", image);
a.setAttribute("download", "canvas.png");
a.click();
到
var post = new XMLHttpRequest();
// I assume your web server have a handler to handle any POST request send to
// '/receive' in the same domain.
// Create a POST request to /receive
post.open("POST", "/receive");
// Send the image data
post.send(image);
您可能需要在服务器端进行一些进一步的处理,以将发布的数据保存到本地文件系统,就像我在 node.js 服务器中所做的那样:
// Handle POST from xxx/receive
app.post('/receive', function(request, respond) {
// The image data will be store here
var body = '';
// Target file path
var filePath = __dirname + '/testWrite/canvas.png';
//
request.on('data', function(data) {
body += data;
});
// When whole image uploaded complete.
request.on('end', function (){
// Get rid of the image header as we only need the data parts after it.
var data = body.replace(/^data:image\/\w+;base64,/, "");
// Create a buffer and set its encoding to base64
var buf = new Buffer(data, 'base64');
// Write
fs.writeFile(filePath, buf, function(err){
if (err) throw err
// Respond to client that the canvas image is saved.
respond.end();
});
});
});
var saveImgae = function() {
var canvas = document.getElementById("myCanvas");
var image = canvas.toDataURL("image/png");
// Create a hidden link to do the download trick.
var a =document.createElement("a");
a.setAttribute("href", image);
a.setAttribute("download", "canvas.png");
a.click();
// Not work for me. It download a file , but without file type and filename is simply download, maybe it works for someone.
// var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
// window.location.href=image; // it will save locally
};
// This is just something like your onclick="saveImage()"
var button = document.querySelector("button");
button.onclick = saveImgae;
// Fakes , I just want to demo the click...
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.font = "40pt Calibri";
context.fillText("My TEXT!", 50, 100);
context.font = "20pt Calibri";
context.fillStyle = 'red';
context.fillText("Tesr", 50, 200);
<canvas id="myCanvas" width="400" height="200" style=" border:1px solid #d3d3d3;"></canvas>
<button id="save">Save image</button>