微信小程序绘图API-canvas(一)

1,049 阅读3分钟

「这是我参与2022首次更文挑战的第26天,活动详情查看:2022首次更文挑战

Canvas简介

这是小程序里的绘制组件,也称画布,我们可以在上面绘制很多东西,比如图片、文字、矩形等。 官方介绍文档:developers.weixin.qq.com/miniprogram… 在小程序代码中先在布局里声明

<canvas canvas-id="poster"></canvas>

本文用uni-app开发小程序来测试

API使用

createCanvasContext(string canvasId, Object this)

这个方法是创建canvas的绘图上下文对象 在方法里面先创建

const ctx = uni.createCanvasContext('poster',this);

矩形、颜色、样式

setFillStyle(string|CanvasGradient color)

设置填充色,可以设置String类型和CanvasGradient类型颜色值,默认颜色为 black。

fill()

对当前路径中的内容进行填充。默认的填充色为黑色。

setStrokeStyle(string color)

描边的颜色,默认颜色为 black。

stroke

对当前路径进行描边,默认颜色为黑色。

rect (number x, number y, number width, number height)

绘制一个矩形

x 矩形路径左上角的横坐标

y 矩形路径左上角的纵坐标

width 矩形路径的宽度

height 矩形路径的高度

  const ctx = uni.createCanvasContext('poster',this);
  ctx.rect(0, 0, 200, 100)
  ctx.setFillStyle('red')
  ctx.fill()
  ctx.draw()			 

在程序里跑上述方法运行可得

c1.png 在cancas布局里画上了一个矩形,左上角坐标(0,0)开始,画一个长200px,宽100px的矩形,填充为红色,即得到。

fillRect(number x, number y, number width, number height)

该方法同上一个方法一个意思,也是画一个矩形,是把

ctx.rect(0, 0, 200, 100) 和 ctx.fill() 合并为一个方法。

strokeRect(number x, number y, number width, number height)

画一个矩形(非填充)。 用 setStrokeStyle 设置矩形线条的颜色,如果没设置默认是黑色。

const ctx = uni.createCanvasContext('poster',this); 
ctx.setStrokeStyle('red') 
ctx.strokeRect(0, 0, 200, 100)
ctx.draw()

得到结果如下

c2.png

clearRect(number x, number y, number width, number height)

清除画布上在该矩形区域内的内容,即可理解为画布上的像素

const ctx = uni.createCanvasContext('poster',this);
 ctx.setFillStyle('red') 
 ctx.fillRect(0, 0, 200, 100)
 ctx.clearRect(20, 20, 50, 50)
ctx.draw()

可以看到结果如下

c3.png 清除掉了(20,20)坐标上的红色。

线条样式

setLineWidth(number lineWidth)

线条的宽度,单位px

setLineCap(string lineCap)

设置线条的端点样式 lineCap 的合法值

butt 向线条的每个末端添加平直的边缘。

round 向线条的每个末端添加圆形线帽。

square 向线条的每个末端添加正方形线帽。(和butt效果差不多,会比butt效果略长)

  const ctx = uni.createCanvasContext('poster',this)
			    ctx.beginPath()
			    ctx.setLineCap('butt')
			    ctx.setLineWidth(10)
			    ctx.moveTo(20, 30)
			    ctx.lineTo(150, 30)
			    ctx.stroke()
			 
			    ctx.beginPath()
			    ctx.setLineCap('round')
			    ctx.setLineWidth(10)
			    ctx.moveTo(20, 50)
			    ctx.lineTo(150, 50)
			    ctx.stroke()
			 
			    ctx.beginPath()
			    ctx.setLineCap('square')
			    ctx.setLineWidth(10)
			    ctx.moveTo(20, 70)
			    ctx.lineTo(150, 70)
			    ctx.stroke()
			 
			    ctx.draw()

效果如下

c4.png

setLineJoin(string lineJoin)

设置线条的交点样式 lineJoin 的合法值
bevel 斜角
round 圆角
miter 尖角

setMiterLimit(number miterLimit)

设置最大斜接长度。斜接长度指的是在两条线交汇处内角和外角之间的距离。当 CanvasContext.setLineJoin()为 miter 时才有效。超过最大倾斜长度的,连接处将以 lineJoin 为 bevel 来显示。

总结

本文主要介绍了部分canvas api,大部分都是互相结合来使用,来达到我们需要的效果,具体的要自己去实验。下一篇继续分享剩下的API使用。