小程序 繪製圓角矩形和圓角圖片

本文介紹了在小程序繪製海報中所要繪製圓角圖片的一種方法

參數介紹

··
ctx : 是指獲取到的當前小程序方法 方法如下

          <canvas canvas-id="DetailsshareCanvas" style="width: 600rpx;height:880rpx;position:relative;" catchtouchmove="myCatchTouch"></canvas> 
        var ctx = wx.createCanvasContext('DetailsshareCanvas');

·
img:所繪製的圖片注意網絡圖片地址要用 wx.getImageInfo 進行加載後的格式
left 和 top:指要繪製的圖片所在canvas 中的位置如下圖點的位置
width 和 height :是指圖片的寬高
w:參數爲小程序適配單位方法和詳情看 https://blog.csdn.net/weixin_43365995/article/details/94392560
fillet :爲要繪製的圓角 半徑
以下傳值均爲 寬爲 750 標準的單位(指寬分爲750份)


在這裏插入圖片描述

  /* 繪製圓角圖片 */ 
  imgfillet(ctx, img, left, top, width, height, w, fillet) {
    //     ctx   圖片  起始點X Y   圖片寬  高   適配單位  圓角半徑
    ctx.beginPath();
    ctx.save();
    left = left / 2 * w;
    top = top / 2 * w;
    width = width / 2 * w;
    height = height / 2 * w;
    fillet = fillet / 2 * w;
    ctx.setLineWidth(1);
    ctx.setStrokeStyle('#ffffff');
    ctx.moveTo(left + fillet, top);           // 創建開始點
    ctx.lineTo(left + width - fillet, top);          // 創建水平線
    ctx.arcTo(left + width, top, left + width, top + fillet, fillet); // 創建弧
    ctx.lineTo(left + width, top + height - fillet);         // 創建垂直線
    ctx.arcTo(left + width, top + height, left + width - fillet, top + height, fillet); // 創建弧
    ctx.lineTo(left + fillet, top + height);         // 創建水平線
    ctx.arcTo(left, top + height, left, top + height - fillet, fillet); // 創建弧
    ctx.lineTo(left, top + fillet);         // 創建垂直線
    ctx.arcTo(left, top, left + fillet, top, fillet); // 創建弧
    ctx.stroke(); // 這個具體幹什麼用的?
    ctx.clip();
    ctx.drawImage(img, left, top, width, height);
    ctx.restore();
    ctx.closePath();
  },

看完不懂或者有其他需求寫不出來請留言博主必回

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章