HTML5 canvas可以绘制图像,我们可以使用ctx.drawImage()方法,该方法需要图像对象和绘制的目标坐标。目标坐标定义图像的左上角相对于画布的左上角。
因为ctx.drawImage()方法需要一个image对象,所以在调用drawImage()之前,我们必须首先创建一个图像并等待它加载完成。我们可以通过使用image对象的onload属性来实现这一点。图像会按照原尺寸画到canvas上面。

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="1000" height="1000"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      var imageObj = new Image();

      imageObj.onload = function() {
        context.drawImage(imageObj, 50, 50);
      };
      imageObj.src = 'https://www.md86.net/resource/upload/20200827/5f477d1b6b85d118.jpg';
    </script>
  </body>
</html>    

效果:

canvas drawImage


要改变图像被画到canvas上面的大小,我们可以向drawImage()方法添加两个附加参数,width和height,这时候图像本身会被缩放导致图像变形。

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="1000" height="1000"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      var x = 188;
      var y = 30;
      var width = 200;
      var height = 200;
      var imageObj = new Image();

      imageObj.onload = function() {
        context.drawImage(imageObj, x, y, width, height);
      };
      imageObj.src = 'https://www.md86.net/resource/upload/20200827/5f477d1b6b85d118.jpg';
    </script>
  </body>
</html>      

效果(变形了):

canvas教程


要使用HTML5 canvas裁剪图像,我们可以向drawImage()方法添加六个附加参数:sourceX、sourceY、sourceWidth、sourceHeight、destWidth和destHeight。这些参数定义要从图像中剪切的矩形的位置和大小以及绘制到画布的大小。

drawImage

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="600" height="500"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      var imageObj = new Image();

      imageObj.onload = function() {
        // 绘制图像的裁剪区域
        var sourceX = 100;
        var sourceY = 130;
        var sourceWidth = 150;
        var sourceHeight = 200;
        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.md86.net/resource/upload/20200827/5f477d1b6b85d118.jpg';
    </script>
  </body>
</html>      

效果:

渝ICP备20006974号-2