【问题标题】:<html5> How can export canvas to image(jpg) and pdf file<html5> 如何将画布导出为图像(jpg)和pdf文件
【发布时间】:2014-10-25 05:22:14
【问题描述】:

我想在画布中绘制图像并将画布导出到图像(jpg)文件和pdf文件..

原来是……点击下载链接,弹出文件保存对话框窗口……

我有一个示例源.. 但在 Chrome 中运行良好,但在 IE11、IE10、IE9、IE8 中无法运行......


    <!DOCTYPE html>
    <html>
    <head>
        <title>toDataURL example</title>
        <style>
          canvas {
            border:solid black 1px;
          }

          img {
            width:400px;
            height:400px;
            border:solid black 1px;
          }
        </style>
    </head>
    <body>
      <h1>Copy graphic using toDataURL</h1>

      <div>
        <button id="copy">Copy canvas image to image element</button> <br />
        <canvas id="MyCanvas" width="400" height="400"  >This browser or document mode doesn't support canvas</canvas>
        <img id="MyPix" src="" width="400" height="400" />

      </div>

      <script>
        // Create some graphics on the canvas.    
        var canvas = document.getElementById("MyCanvas");
        if (canvas.getContext) {
          var ctx = canvas.getContext("2d");
          ctx.fillStyle = "white";
          ctx.beginPath();
          ctx.rect(5, 5, 300, 250);
          ctx.fill();
          ctx.stroke();
          ctx.arc(150, 150, 100, 0, Math.PI, false);
          ctx.stroke();
       }

        // catch the click from the button and copy the graphic
        document.getElementById("copy").addEventListener("click", function () {
          var canvas1 = document.getElementById("MyCanvas");
          if (canvas1.getContext) {
            var ctx = canvas1.getContext("2d");                // Get the context for the canvas.
            var myImage = canvas1.toDataURL("image/png");      // Get the data as an image.
          }
          var imageElement = document.getElementById("MyPix");  // Get the img object.
          //imageElement.src = myImage;                           // Set the src to data from the canvas.
        window.location = myImage; 


        }, false);

      </script>
    </body>
    </html> 

【问题讨论】:

    标签: html image pdf export jpeg


    【解决方案1】:

    使用 toDataUrl() 函数

    var datImage = canvas.toDataURL("image/png");
    document.write('<img src="'+datImage+'"/>');
    

    此代码将获取画布的内容,并将其转换为 PNG 图像,并将其写入屏幕。

    注意:在您将图像绘制到画布上后,这将不起作用,因为它会更改数据 URL。

    希望这有帮助!

    【讨论】:

    猜你喜欢
    • 2020-02-06
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 2016-11-05
    • 2014-01-24
    • 2014-03-21
    • 2021-11-25
    相关资源
    最近更新 更多