按下按钮时,HTML画布将JPG图像输出到服务器

Posted

技术标签:

【中文标题】按下按钮时,HTML画布将JPG图像输出到服务器【英文标题】:HTML canvas output JPG Image to server when button is pressed 【发布时间】:2015-07-11 15:58:38 【问题描述】:

所以我有一个创建画布的脚本,我想知道在 html 页面上是否有一个按钮,当单击它时,它将将该页面上的画布作为 jpg 图像保存到 Web 服务器。

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas"   style=" border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
window.onload = function()
     var canvas = document.getElementById("myCanvas");
     var context = canvas.getContext("2d");
     var imageObj = new Image();
     imageObj.onload = function()
         context.drawImage(imageObj, 0, 0);
         context.font = "40pt Calibri";
         context.fillText("My TEXT!", 50, 100);
         context.font = "20pt Calibri";
         context.fillStyle = 'red';
         context.fillText("Tesr", 50, 200);
     ;
     imageObj.src = "Assets/Background2.png"; 
;
</script>

<button onclick="Saveimage"></button>

</body>
</html>

【问题讨论】:

看看How To Save Canvas As An Image With canvas.toDataURL()? 这会在画布创建时保存。单击按钮时我需要它来保存图像 创建了一个答案,看看吧。 【参考方案1】:

从我在评论中给出的主题来看,它给出了奇怪的结果。 由于我不知道您是否坚持将按钮设为 &lt;button&gt; 而不是 &lt;a&gt;,因此我创建了一个解决方法以使其看起来有效。

编辑:

如果要将图像保存到服务器。

改变

  // 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"   style=" border:1px solid #d3d3d3;"></canvas>
<button id="save">Save image</button>

【讨论】:

有没有办法把它保存到服务器而不是下载它? 服务器将如何处理它,你是否创建了一个特定的 url(如 /images),当我向它发送一个 post 请求时,它会将它保存到你的文件系统中?【参考方案2】:

如果imgsrc 不是crossOrigin 可以利用canvas.toDataURL() , $.post()canvasdata URI 发送到服务器,否则,将img src 设置为@98766防止出错

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.


    window.onload = function () 
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    var button = document.getElementsByTagName("button")[0];
    var imageObj = new Image();
    imageObj.onload = function () 
        context.drawImage(imageObj, 0, 0);
        context.font = "40pt Calibri";
        context.fillText("My TEXT!", 50, 100);
        context.font = "20pt Calibri";
        context.fillStyle = "red";
        context.fillText("Tesr", 50, 200);
    ;
    imageObj.src = "/path/to/image";

    button.onclick = function (e) 
        var data = canvas.toDataURL();
        var post = new XMLHttpRequest();
        post.open("POST", "/echo/html/");
        post.onload = function (e) 
            console.log(this.responseText)
        ;
        post.send("html=" + encodeURIComponent(data));
    ;
;

jsfiddle http://jsfiddle.net/4fdnd4ve/

【讨论】:

"按钮代码是什么样的?" ?请参阅onclick handler 中的帖子 您的代码似乎不起作用。无论如何,您可以将整个 html 文件发送给我,因为我所拥有的对我不起作用。如此处所见link

以上是关于按下按钮时,HTML画布将JPG图像输出到服务器的主要内容,如果未能解决你的问题,请参考以下文章

如何将画布保存为html5中的图像?

将 HTML5 画布图像保存到数据库

同一画布上的多个图形

java将图像添加到画布

java将图像添加到画布

图像到画布 / HTML5 转换 [关闭]