HLJ 发布于
2018-08-20 16:57:25

HTML5 Canvas drawImage()方法加载图像数据URL

要使用图像数据URL加载画布,我们可以进行AJAX调用以获取数据URL,使用URL创建图像对象,然后使用画布上下文的drawImage()方法将图像绘制到画布上。
html代码:
<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      function loadCanvas(dataURL) {
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');

        // load image from data url
        var imageObj = new Image();
        imageObj.onload = function() {
          context.drawImage(this, 0, 0);
        };

        imageObj.src = dataURL;
      }
      
      // make ajax call to get image data url
      var request = new XMLHttpRequest();
      request.open('GET', 'https://www.html5canvastutorials.com/demos/assets/dataURL.txt', true);
      request.onreadystatechange = function() {
        // Makes sure the document is ready to parse.
        if(request.readyState == 4) {
          // Makes sure it's found the file.
          if(request.status == 200) {
            loadCanvas(request.responseText);
          }
        }
      };
      request.send(null);

    </script>
  </body>
</html>

当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2018-08-20/176.html
最后生成于 2023-06-18 18:38:16
此内容有帮助 ?
0