微信小程序用canvas画圆角矩形
时间: 2023-09-29 16:08:32 浏览: 291
要在微信小程序中使用Canvas绘制圆角矩形,可以使用以下步骤:
1. 在wxml文件中添加Canvas组件:
```html
<canvas canvas-id="myCanvas"></canvas>
```
2. 在js文件中获取Canvas对象:
```javascript
const ctx = wx.createCanvasContext('myCanvas')
```
3. 使用Canvas API绘制圆角矩形:
```javascript
// 设置填充色
ctx.setFillStyle('#f00')
// 设置边框颜色
ctx.setStrokeStyle('#000')
// 设置边框宽度
ctx.setLineWidth(2)
// 绘制圆角矩形
ctx.moveTo(x + r, y)
ctx.lineTo(x + w - r, y)
ctx.arc(x + w - r, y + r, r, -Math.PI / 2, 0)
ctx.lineTo(x + w, y + h - r)
ctx.arc(x + w - r, y + h - r, r, 0, Math.PI / 2)
ctx.lineTo(x + r, y + h)
ctx.arc(x + r, y + h - r, r, Math.PI / 2, Math.PI)
ctx.lineTo(x, y + r)
ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 3 / 2)
ctx.closePath()
// 填充圆角矩形
ctx.fill()
// 绘制边框
ctx.stroke()
// 绘制完成
ctx.draw()
```
其中,x、y、w、h、r分别代表圆角矩形的左上角x坐标、左上角y坐标、宽度、高度、圆角半径。可以根据自己的需求来修改这些值。
4. 在wxml文件中显示Canvas:
```html
<canvas canvas-id="myCanvas" style="width:{{canvasWidth}}px;height:{{canvasHeight}}px;"></canvas>
```
其中,canvasWidth和canvasHeight是根据Canvas绘制的圆角矩形的大小来计算的。
阅读全文
相关推荐














