【问题标题】:Export HTML5 Canvas to Image to Desired Web Directory将 HTML5 Canvas 导出到图像到所需的 Web 目录
【发布时间】:2015-11-13 03:31:10
【问题描述】:

我正在使用以下 JavaScript 将 HTML5 Canvas 转换为 .PNG 图像:

   function imageMe() {
        var canvasImage = document.getElementById("c");
        var img = canvasImage.toDataURL("image/png");

        document.write('<img src="' + img + '"/>');
    }

这需要用户右键单击并将图像保存到某个位置。

我的目标是在单击时将图像保存到 Web 目录(覆盖具有相同名称的图像),而无需用户下载然后上传图像。

我的问题是如何将点击后的图像保存到我网站中的正确目录?如果我正在生成图像客户端等,我还需要上传 Ajax 文件吗?

【问题讨论】:

    标签: javascript jquery html canvas


    【解决方案1】:

    如果您使用网络服务器提供网页服务

    您应该使用@BhavinSolanki 提供的出色答案。

    如果您想让用户将画布作为图像保存在自己的计算机上

    您可以使用 Eli Grey 的 FileSaverJS 脚本:https://github.com/eligrey/FileSaver.js/

    我不知道为什么,但是...,当前 GitHub 版本的 FileSaverJS 不适合我(版本 1.1.20150716)。因此,对于以下演示,我使用的是 CloudFlare.com 上托管的先前版本。

    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    
    var img = new Image()
    img.crossOrigin = "anonymous";
    img.onload = function() {
      // draw an annotated image on the canvas
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img, 0, 0);
      ctx.fillStyle = 'black';
      ctx.fillRect(0, img.height - 30, img.width, 30);
      ctx.fillStyle = 'white';
      ctx.font = '14px verdana';
      ctx.textAlign = 'center';
      ctx.fillText('Hey, Koolaid Man!', img.width / 2, img.height - 10);
    }
    img.src = "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/KoolAidMan.png";
    
    // save the canvas as an image on the users local drive
    $("#save").on('click', function() {
      canvas.toBlob(function(blob) {
        saveAs(blob, "KoolaidMan.png");
      });
    });
    body{ background-color: ivory; }
    #canvas{border:1px solid red; margin:0 auto; }
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src='https://rawgit.com/eligrey/Blob.js/master/Blob.js'></script>
    <script src='https://rawgit.com/eligrey/canvas-toBlob.js/master/canvas-toBlob.js'></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js'></script>
    
    <button id="save">Save</button>
    <br>
    <canvas id="canvas" width=300 height=300></canvas>

    【讨论】:

    • 非常有帮助。我使用的是 Web 服务器,所以我将重点介绍如何通过直接 jQuery(非 PHP)上传
    • 很高兴我能帮上忙。您使用的是哪个网络服务器?
    • IIS (Visual Studio) 用于本地开发。用于部署的 IIS (Azure)
    猜你喜欢
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 2016-06-11
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    相关资源
    最近更新 更多