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
posted @ 2016-06-13 09:47  火腿骑士  阅读(356)  评论(0编辑  收藏  举报