小程序——canvas圓角矩形(有無填充色)

1.繪制無填充色圓角矩形(這里主要是線條繪制)

function roundRect(ctx,x,y,w,h,r){  //繪制圓角矩形(無填充色))
  ctx.save();
  if(w < 2 * r){
    r = w / 2;
  }
  if(h < 2 * r){
    r = h / 2;
  }
  ctx.beginPath();
  ctx.setFillStyle("#ccc");
  ctx.setStrokeStyle('#111');
  ctx.setFillStyle("#ccc");
  ctx.setLineWidth(1);
  ctx.setFillStyle("#ccc");
  ctx.moveTo(x + r , y);
  ctx.arcTo(x + w, y, x + w, y + h, r);
  ctx.arcTo(x + w, y + h, x , y + h, r);
  ctx.arcTo(x, y + h, x, y, r);
  ctx.arcTo(x, y, x + w, y , r);
  ctx.stroke();
  ctx.closePath();
}

2.繪制有填充色圓角矩形 (通過setLineJoin設(shè)置交點(diǎn)樣式)

function roundRectColor(context, x, y, w, h, r) {  //繪制圓角矩形(純色填充)
  context.save();
  context.setFillStyle("#abc"); 
  context.setStrokeStyle('#abc')
  context.setLineJoin('round');  //交點(diǎn)設(shè)置成圓角
  context.setLineWidth(r);
  context.strokeRect(x + r/2, y + r/2, w - r , h - r );
  context.fillRect(x + r, y + r, w - r * 2, h - r * 2);
  context.stroke();
  context.closePath();
}

調(diào)用:

let context = wx.createCanvasContext('mycanvas'); //搞一塊畫板
context.setFillStyle("#fff"); //設(shè)置純色填充
context.fillRect(0, 0, 335, 556);

roundRectColor(context,200, 20, 100, 100,16);
roundRect(context, 20, 20, 100, 100, 16);

效果:


捕獲.PNG
//移動端
function roundRectColor(context, x, y, w, h, r) {  //繪制圓角矩形(純色填充)
  context.save();
  context.fillStyle = "#fff";
  context.strokeStyle = '#fff';
  context.lineJoin = 'round';  //交點(diǎn)設(shè)置成圓角
  context.lineWidth = r;
  context.strokeRect(x + r/2, y + r/2, w - r , h - r );
  context.fillRect(x + r, y + r, w - r * 2, h - r * 2);
  context.stroke();
  context.closePath();
}

另,記錄一個(gè)遇到的報(bào)錯
1.安卓機(jī):
tempFilePath:create bitmap failed
2.ios:
tempFilePath:failed no image;
網(wǎng)上的延時(shí)什么的都寫了,還報(bào)錯,原因是canvas不能用 display:none

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容