zoukankan      html  css  js  c++  java
  • H5保存图片

    摘抄代码:

    <html>
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <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>
    

      备注: 保存图片 -- PC端和移动端正常浏览器可用(微信不可用)

          下载图片 -- 仅PC可用

  • 相关阅读:
    Analysis Services 查询性能十大最佳实践(转)
    谈谈一年来对“数据仓库”概念的困惑、探索和感悟(转)
    用sql语句添加删除主键
    大文件流操作及编码
    SQL Server CONVERT() 函数
    正则表达式提取案例1
    解析SQL SERVER存储过程返回值
    文件操作类Path
    HTTP状态码
    自己写的遮罩层效果
  • 原文地址:https://www.cnblogs.com/handsome-jm/p/8287336.html
Copyright © 2011-2022 走看看