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
     
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM