700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 微信小程序canvas绘制自定义圆角矩形

微信小程序canvas绘制自定义圆角矩形

时间:2021-11-24 03:04:38

相关推荐

微信小程序canvas绘制自定义圆角矩形

分享一个可以自定义每个角的圆角的canvas方法:

/** @description canvas 绘制自定义圆角的矩形(默认填充色)-hyf* x-位置x坐标, y-位置y坐标, w-元素宽度, h-元素高度, r-圆角* if config = color // 默认填充色* else config = {* type: fill / stroke / both,填充/描边/填充和描边* fillColor: color, //填充色* strokeColor: color, //描边色* round:{ // 配置哪个方向的角是圆角,默认不传全是圆角* leftTop: boole, // 是否圆角* leftBottom: boole, // 是否圆角* rightTop: boole, // 是否圆角* rightBottom: boole, // 是否圆角* }}**/roundRect (ctx, x, y, w, h, r, config) {let color = 'transparent'if (typeof config === 'string') {color = config}ctx.save()// 开始绘制ctx.beginPath()// 因为边缘描边存在锯齿,最好指定使用 transparent 填充if (config.type) {if (config.type === 'fill') {ctx.setFillStyle(config.fillColor || 'transparent')} else if (config.type === 'stroke') {ctx.setStrokeStyle(config.strokeColor || 'transparent')} else if (config.type === 'both') {ctx.setFillStyle(config.fillColor || 'transparent')ctx.setStrokeStyle(config.strokeColor || 'transparent')}} else {ctx.setFillStyle(color)}if (!config.round || config.round.leftTop) {// 绘制左上角圆弧ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)// 绘制border-topctx.moveTo(x + r, y)} else {// 绘制border-topctx.moveTo(x, y + r)ctx.lineTo(x, y)ctx.lineTo(x + r, y)}ctx.lineTo(x + w - r, y)if (!config.round || config.round.rightTop) {// 绘制右上角圆弧ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)} else {ctx.lineTo(x + w - r, y)ctx.lineTo(x + w, y)ctx.lineTo(x + w, y + r)}// 绘制border-rightctx.lineTo(x + w, y + h - r)if (!config.round || config.round.rightBottom) {// 绘制右下角圆弧ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)} else {ctx.lineTo(x + w, y + h - r)ctx.lineTo(x + w, y + h)ctx.lineTo(x + w - r, y + h)}// 绘制border-bottomctx.lineTo(x + r, y + h)if (!config.round || config.round.leftBottom) {// 绘制左下角圆弧ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)} else {ctx.lineTo(x + r, y + h)ctx.lineTo(x, y + h)ctx.lineTo(x, y + h - r)}// 绘制border-leftctx.lineTo(x, y + r)if (config.type) {if (config.type === 'fill') {ctx.fill()} else if (config.type === 'stroke') {ctx.stroke()} else if (config.type === 'both') {ctx.stroke()ctx.fill()}} else {ctx.fill()}ctx.closePath()// 剪切ctx.clip()ctx.restore()}

用法:

//html<canvas canvas-id="canvas" class="canvas"></canvas>// jslet ctx = wx.createCanvasContext('canvas', this)// 1. canvas 坐标(0,0)位置绘制 一个长200px,高100px,四个角都是圆角,圆角20px,的红色椭圆按钮roundRect(ctx, 0, 0, 200, 100, 20, 'red')// 2. canvas 坐标(0,0)位置绘制 一个长200px,高100px,左上左下角是圆角,圆角20px,的红色椭圆按钮roundRect(ctx, 0, 0, 200, 100, 20, {leftTop: true, leftBottom: true, rightTop: false, rightBottom: false})

2.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。