zoukankan      html  css  js  c++  java
  • canvas转图片

    <script>
      var canvas, context2D, canvasimg, context2Dimg ,fontSize = 100;
       
      window.onload = function() {
      canvas =document.getElementById("canvas");
      context2D = canvas.getContext("2d");
      canvasimg =document.getElementById("canvasimg");
      context2Dimg = canvasimg.getContext("2d");
      context2D.font ="100px 黑体";
      context2D.fillText("V", 0, fontSize);
       
      //添加range事件
      document.getElementById("range").addEventListener("mouseup", function() {
      fontSize = this.value;
      context2D.font = this.value +"px 黑体";
      context2D.clearRect(0, 0, canvas.width, canvas.height);
      context2D.fillText("V", 0, fontSize);
      });
      }
       
      function go(){
       
      var img = convertCanvasToImage(document.getElementById("canvas"));
      context2Dimg.clearRect(0, 0, canvas.width, canvas.height);
      context2Dimg.drawImage(img, 0, 0);
       
      //需要将Base64编码转换为Blob(一段二进制数据)对象 ,后才能生成文件下载 参考 http://javascript.ruanyifeng.com/htmlapi/file.html#toc0
      var blob = new Blob([Base64Binary.decodeArrayBuffer(canvas.toDataURL("image/png").substring(22))]); //删除字符串前的提示信息 "data:image/png;base64,"
      var a = document.createElement("a");
      a.href = window.URL.createObjectURL(blob);
      a.download = "test.png";
      a.textContent = "下载图片->";
      document.body.appendChild(a);
      //a.click();
      show();
      }
       
      //将图片显示在网页中
      function show(){
      var img = convertCanvasToImage(document.getElementById("canvas"));
      document.body.appendChild(img);
      }
       
      //将canvas变成图片png
      function convertCanvasToImage(canvas) {
      var image = new Image();
      image.style.border="1px solid blue";
      image.src = canvas.toDataURL("image/png");
      return image;
      }
      </script>
      <style>
      input[type=range]:before { content: attr(min); padding-right: 5px; }
      input[type=range]:after { content: attr(max); padding-left: 5px;}
      </style>
      </head>
      <body>
      <input id="range" type="range" name="range" min="100" max="500" step="100" value="100" />
      <canvas id="canvas" style="border:1px solid red;" width=500 height=500></canvas>
      <button onclick="go();">canvas转图片,再加载到右边canvas中</button>
      <canvas id="canvasimg" style="border:1px solid red;" width=500 height=500></canvas>
      </body>
      <script>
      //base64转Blob 地址 https://github.com/danguer/blog-examples/blob/master/js/base64-binary.js
  • 相关阅读:
    763. 划分字母区间(贪心算法)
    1282. 用户分组(贪心算法)
    698. 划分为k个相等的子集
    560. 和为K的子数组
    面试题 16.10. 生存人数
    Python:对列表进行排序并相应地更改另一个列表?
    数据竞赛总结
    面试提问之请你介绍一下xxx方法
    常用数学符号读法
    round() 函数
  • 原文地址:https://www.cnblogs.com/fx2008/p/5579580.html
Copyright © 2011-2022 走看看