• 将HTML5 Canvas的内容保存为图片借助toDataURL实现


    将HTML5 Canvas的内容保存为图片主要思想是借助Canvas自己的API - toDataURL()来实现,具体实现如下,感兴趣的朋友可以参考下哈,希望对你有所帮助

    <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
    }
    </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> 

     . 关于toDataURL(type, ratio)函数,参数type在image/png,image/jpeg,image/svg+xml等 MIME类型中选择(可以不填,默认是image/png)。如果是type = “image/jpeg”,可以有第二个参数,如果第二个参数ratio的值在0-1之间,则表示JPEG的质量等级,否则使用浏览器内置默认质量等级。

  • 相关阅读:
    leetcode643.滑动窗口例题
    BZOJ4195 离散化+并查集
    luogu线性表刷题
    2021-5-29 周报博客
    2021-5-28 日报博客
    2021-5-27 日报博客
    2021-5-26 日报博客
    2021-5-25 日报博客
    2021-5-24 日报博客
    梦断代码阅读笔记之二
  • 原文地址:https://www.cnblogs.com/chengqiaoli/p/5382835.html
Copyright © 2020-2023  润新知