uni-app canvas绘制海报流程的一些记录

1,232 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第5天,点击查看活动详情

canvas介绍

官方文档:uniapp.dcloud.net.cn/api/canvas/… 使用方式跟微信小程序基本一致,通过其中api的结合就可以绘制出自己想要的海报或者效果。

绘制流程

布局定义

在我们的布局里要声明canvas的定义如下,可以声明class布局样式,width和height是必须的,因为如果没有就绘制不了。

canvas-id也是必须的,我们需要通过id找到对一个你的canvas对象,来做操作

<canvas class="poster_canvas" canvas-id="mini_poster"
    :style="{ width: canvasW + 'px', height: canvasH + 'px' }">
</canvas>

绘制背景图

所有绘制操作都要通过createCanvasContext创建好canvas对象来进行, 这里this.bgShareInvite 是一个图片url,这里是获取到图片的信息,然后通过 drawImage 绘制出来 参数需要绘制的坐标(x,y)和绘制的图片宽高。

let ctx = uni.createCanvasContext('mini_poster', this)
let info = await uni.getImageInfo({
    src: this.bgShareInvite
})
console.log('info:', info[1]);
//绘制背景图
ctx.drawImage(info[1].path, 0, 0, this.canvasW, this.canvasH)												

绘制背景

可以绘制各种底色的背景,带圆角或者不带!这里建议封装好2个方法,如下,然后在对应界面引用,传入我们需要的参数来调用。

const roundedRect = (ctx, x, y, width, height, radius) => {
	ctx.moveTo(x + radius, y);
	ctx.arcTo(x + width, y, x + width, y + height, radius);
	ctx.arcTo(x + width, y + height, x, y + height, radius);
	ctx.arcTo(x, y + height, x, y, radius);
	ctx.arcTo(x, y, x + radius, y, radius);
}

export const drawRoundedRect = (ctx, strokeStyle, fillStyle, x, y, width, height, radius) => {
	ctx.beginPath();
	roundedRect(ctx, x, y, width, height, radius);
	ctx.strokeStyle = strokeStyle;
	ctx.fillStyle = fillStyle;
	ctx.stroke();
	ctx.fill();
}


//绘制圆角矩形
let bgWhiteW = 484
let bgWhiteH = 604
let radius = 20
drawRoundedRect(ctx, '#ffffff', '#ffffff', 20, 20, bgWhiteW, bgWhiteH, radius)

绘制本地图片

这个没什么特别,跟绘制网络图片的差别在于,不需要在获取图片的信息了,直接传递图片路径作为参数,可以直接绘制。

//绘制内部背景logo
let bgLogoW = 336
let bgLogoH = 142
let bgLogoX = this.canvasW / 2 - bgLogoW / 2
let bgLogoY = 70
ctx.drawImage('../../static/image/bg-login-tips.png', bgLogoX, bgLogoY, bgLogoW, bgLogoH)

绘制文字

主要注意2个api的使用,一个是measureText,测量文字的宽度。

一个是fillText绘制文字,参数传对应的文字坐标。同时注意的还有textAlign方法,这个是设置文字的绘制位置是中心还是左侧、右侧,以x坐标为标准,绘制的起始点在中心、左侧、右侧三个选项。

let tips = '仅限受邀用户才能参加内购活动'
let tipsW = ctx.measureText(tips).width
let bottomTvX = this.canvasW / 2
let bottomTvY = 85;
const fz30 = uni.$u.getPx('32rpx')
ctx.fillStyle = '#333333'
ctx.textAlign = "center"
ctx.setFontSize(fz30)
ctx.fillText(tips, bottomTvX, bottomTvY)			
				

总结

基本上绘制海报的流程,都是用到以上几个api的结合,可以绘制出我们想要的效果。其中要根据设计稿的排版来进行坐标的设置,然后做好划分,先绘制哪一部分,在绘制下一部分,做好划分,一定能绘制出想要的效果!