美文网首页
小程序——canvas圆角矩形(有无填充色)

小程序——canvas圆角矩形(有无填充色)

作者: 汀上 | 来源:发表于2019-03-19 11:42 被阅读0次

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设置交点样式)

function roundRectColor(context, x, y, w, h, r) {  //绘制圆角矩形(纯色填充)
  context.save();
  context.setFillStyle("#abc"); 
  context.setStrokeStyle('#abc')
  context.setLineJoin('round');  //交点设置成圆角
  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();
}

调用:

let context = wx.createCanvasContext('mycanvas'); //搞一块画板
context.setFillStyle("#fff"); //设置纯色填充
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';  //交点设置成圆角
  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();
}

另,记录一个遇到的报错
1.安卓机:
tempFilePath:create bitmap failed
2.ios:
tempFilePath:failed no image;
网上的延时什么的都写了,还报错,原因是canvas不能用 display:none

相关文章

网友评论

      本文标题:小程序——canvas圆角矩形(有无填充色)

      本文链接:https://www.haomeiwen.com/subject/bahspqtx.html