使用 Javascript 下载 HTML 画布并将其保存为图像

使用 Javascript 下载 HTML 画布并将其保存为图像

了解如何允许用户以图像的形式下载和保存 HTML 画布的内容。



HTML 画布可用于多种应用,例如绘制图像、创建图表

、动画等等。您可以在 Javascript 中使用的一个特别有用的功能是能够将画布捕获为图像(根据您选择的格式),并允许用户一键下载此图像。​

使用 Javascript 从画布中检索和下载图像数据

允许用户将 HTML 画布下载为图像涉及两个步骤。

首先,您必须从画布元素本身检索图像数据,这可以使用

canvas.toDataURL()

可以像这样使用的函数:

var imageData = canvas.toDataURL( type, encoderOptions )

这两个参数都是可选的。类型参数指定图像格式,默认情况下设置为 image/png。编码器选项参数指定默认设置为 0.92 的图像质量。

接下来,您需要使用从 toDataURL() 函数中检索到的数据创建一个临时链接并自动激活它,以便可以将每个步骤合并到一个函数中。

这可以通过将 toDataURL() 的返回值分配给您在 Javascript 函数中手动创建的锚元素的 href 属性来完成,然后可以使用 click() 函数自动激活它。

某些浏览器仅允许激活位于 HTML 文档正文中的锚元素,要解决此问题,您可以暂时将其添加到文档中,激活链接,然后立即将其删除。这对用户来说是不可见的,因为它几乎立即发生。

// create temporary link  
var tmpLink = document.createElement( 'a' );  
tmpLink.download = 'image.png'; // set the name of the download file 
tmpLink.href = imageData;  
  
// temporarily add link to body and initiate the download  
document.body.appendChild( tmpLink );  
tmpLink.click();  
document.body.removeChild( tmpLink );

这将启动画布图像的下载。

下载并保存 HTML 画布作为图像示例

作为将 HTML 画布下载为图像的快速示例,我们将创建一个新画布,在其上绘制一些形状,然后使用上述代码启动画布图像的下载。

创建 HTML 画布和下载按钮:

<canvas id="download_canvas" width="210" height="160"></canvas><br>  
<button onclick="downloadCanvas()">Download Me!</button>

用一些基本形状初始化画布:

var canvas = document.getElementById( 'download_canvas' );  
  
window.onload = function(){  
    init();  
};  
  
function init(){  
    var context = canvas.getContext( '2d' );  
  
    context.beginPath();  
  
    // draw a blue rectangle 
    context.fillStyle = 'blue';  
    context.fillRect( 10, 10, 150, 100 );  
  
    // draw a red rectangle 
    context.fillStyle = 'red';  
    context.fillRect( 60, 50, 150, 100 );  
}

创建在单击下载按钮时下载图像的函数:

function downloadCanvas(){  
    // get canvas data  
    var image = canvas.toDataURL();  
  
    // create temporary link  
    var tmpLink = document.createElement( 'a' );  
    tmpLink.download = 'image.png'; // set the name of the download file 
    tmpLink.href = image;  
  
    // temporarily add link to body and initiate the download  
    document.body.appendChild( tmpLink );  
    tmpLink.click();  
    document.body.removeChild( tmpLink );  
}

单击下载按钮时,应提示用户下载画布图像:

使用 Javascript 示例将画布下载为图像

<html>
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <head>
        <script>
            window.onload = function () {
                draw();
                var saveButton = document.getElementById("saveImageBtn");
                bindButtonEvent(saveButton, "click", saveImageInfo);
                var dlButton = document.getElementById("downloadImageBtn");
                bindButtonEvent(dlButton, "click", saveAsLocalImage);
            };
            function draw() {
                var canvas = document.getElementById("thecanvas");
                var ctx = canvas.getContext("2d");
                ctx.fillStyle = "rgba(125, 46, 138, 0.5)";
                ctx.fillRect(25, 25, 100, 100);
                ctx.fillStyle = "rgba( 0, 146, 38, 0.5)";
                ctx.fillRect(58, 74, 125, 100);
                ctx.fillStyle = "rgba( 0, 0, 0, 1)"; // black color
                ctx.fillText("Gloomyfish - Demo", 50, 50);
            }
            function bindButtonEvent(element, type, handler) {
                if (element.addEventListener) {
                    element.addEventListener(type, handler, false);
                } else {
                    element.attachEvent('on' + type, handler);
                }
            }
            function saveImageInfo() {
                var mycanvas = document.getElementById("thecanvas");
                var image = mycanvas.toDataURL("image/png");
                var w = window.open('about:blank', 'image from canvas');
                w.document.write("<img src='" + image + "' alt='from canvas'/>");
            }
            function saveAsLocalImage() {
                var myCanvas = document.getElementById("thecanvas");
                // here is the most important part because if you dont replace you will get a DOM 18 exception.
                //var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream;Content-Disposition: attachment;filename=foobar.png");
                var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
                //window.location.href = image; // it will save locally
                // create temporary link  
                var tmpLink = document.createElement('a');
                tmpLink.download = 'image.png'; // set the name of the download file 
                tmpLink.href = image;

                // temporarily add link to body and initiate the download  
                document.body.appendChild(tmpLink);
                tmpLink.click();
                document.body.removeChild(tmpLink);
            }
        </script>
    </head>
    <body bgcolor="#E6E6FA">
        <div>
            <canvas width=200 height=200 id="thecanvas"></canvas>
            <button id="saveImageBtn">Save Image</button>
            <button id="downloadImageBtn">Download Image</button>
        </div>
    </body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值