Canvas绘制圆角图片

效果图:

思路:

  1. 先绘制一个圆角长方形
  2. 在画布中裁剪下来
  3. 在圆角长方形内绘制图片
  4. 图片四个角超出圆角长方形的区域被隐藏

具体代码:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Canvas绘制时钟</title>
    <style>
      .wrapper {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 800px;
      }
      .left {
        margin-right: 100px;
      }
      #canvas {
        border: 1px solid #ccc;
      }
      #img {
        width: 270px;
        height: 300px;
        margin-right: 60px;
        border: 2px solid #ccc;
      }
    </style>
  </head>
  <body>
    <div class="wrapper">
      <div class="left">
        <p>原图 270 * 300</p>
        <img id="img" src="./3.jpeg" />
      </div>
      <div class="right">
        <p>canvas 300 * 400</p>
        <p>图片 200 * 300</p>
        <canvas id="canvas" width="300" height="400"></canvas>
      </div>
    </div>
    <script>
      let canvas = document.getElementById('canvas');
      let ctx = canvas.getContext('2d');

      let img = document.getElementById('img');
      img.onload = function () {
        handleDraw();
      };

      handleDraw = () => {
        handleBorderRect(ctx, 10, 10, 200, 300, 14, '#ccc');
        ctx.clip();
        ctx.drawImage(img, 10, 10, 200, 300);
      };

      handleBorderRect = (ctx, x, y, w, h, r, color) => {
        ctx.beginPath();
        // 左上角
        ctx.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI);
        ctx.moveTo(x + r, y);
        ctx.lineTo(x + w - r, y);
        ctx.lineTo(x + w, y + r);
        // 右上角
        ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI);
        ctx.lineTo(x + w, y + h - r);
        ctx.lineTo(x + w - r, y + h);
        // 右下角
        ctx.arc(x + w - r, y + h - r, r, 0, 0.5 * Math.PI);
        ctx.lineTo(x + r, y + h);
        ctx.lineTo(x, y + h - r);
        // 左下角
        ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, Math.PI);
        ctx.lineTo(x, y + r);
        ctx.lineTo(x + r, y);

        ctx.fillStyle = color;
        ctx.fill();
        ctx.closePath();
      };
    </script>
  </body>
</html>
View Code

如果在Taro中食用,需要改动一下:

  1. 将img.onload换成Taro.getImageInfo
  2. 在getImageInfo的success回调中调用绘制图片的方法handleDraw
     
 

 

posted @ 2021-01-07 10:49  巫瞅瞅  阅读(2426)  评论(0编辑  收藏  举报