HLJ 发布于
2018-08-20 10:55:51

HTML5 Canvas drawImage()方法裁剪图像

要使用HTML5 Canvas裁剪图像,我们可以向drawImage()方法,sourceX,sourceY,sourceWidth,sourceHeight,destWidth和destHeight添加六个额外的参数。 这些参数定义了我们想要从图像中剪切出来的矩形的位置和大小。
html代码:
<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      var imageObj = new Image();

      imageObj.onload = function() {
        // draw cropped image
        var sourceX = 150;
        var sourceY = 0;
        var sourceWidth = 150;
        var sourceHeight = 150;
        var destWidth = sourceWidth;
        var destHeight = sourceHeight;
        var destX = canvas.width / 2 - destWidth / 2;
        var destY = canvas.height / 2 - destHeight / 2;

        context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
      };
      imageObj.src = 'https://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
    </script>
  </body>
</html>
当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2018-08-20/150.html
最后生成于 2023-06-18 18:37:51
此内容有帮助 ?
0