原生JS 将canvas生成图片

核心代码:
<script type="text/javascript">
  // Converts image to canvas; returns new canvas element
  function convertImageToCanvas(image) {
    var canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    canvas.getContext("2d").drawImage(image, 0, 0);
    return canvas;
  }
  // Converts canvas to an image
  function convertCanvasToImage(canvas) {
    var image = new Image();
    image.src = canvas.toDataURL("image/png");
    return image;
  }
</script>
需要注意:
跨域的图片需要设置crossOrigin="Anonymous"属性,然后等图片加载完成后才能使用 toDataURL() 方法
  否则会报错:
    Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

  图片转canvas画布的时候(convertImageToCanvas)
  需要注意的是:
    如果图片原尺寸是200px*200px, 通过样式改变图片的宽高,则 image.width 和 image.height 获取的是改变后的宽高
    如果改变后的宽高小于原尺寸,那么将不能完整的把图片完整的绘制出来
    因为drawImage(image, 0, 0)是根据图片原尺寸进行绘制的
示例:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style type="text/css">
    /*img {
      width: 100px;
    }*/
  </style>
</head>
<body>
<!--<img id="tulip" src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2256920272,2188849592&fm=26&gp=0.jpg" alt="" crossOrigin="Anonymous">-->

<img id="tulip" src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=158393800,2846304514&fm=26&gp=0.jpg" alt="" crossOrigin="Anonymous">
</body>
</html>
<script>
  // Converts image to canvas; returns new canvas element
  function convertImageToCanvas(image) {
    var canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    canvas.getContext("2d").drawImage(image, 0, 0);
    return canvas;
  }

  // Converts canvas to an image
  function convertCanvasToImage(canvas) {
    var image = new Image();
    image.src = canvas.toDataURL("image/png");
    return image;
  }

  function drawImage(img) {
    var cs = convertImageToCanvas(img);
    var image = convertCanvasToImage(cs);
    document.body.appendChild(image);
  }

  window.onload = function () {
    var img = document.getElementById("tulip");
    img.onload = drawImage(img);
  }
</script>

参考链接:

posted @ 2019-03-07 15:59  果冻丨小布丁  阅读(1624)  评论(0编辑  收藏  举报