简介
可通过选择图片、配置图片间距、是否展示合伙人等,使用canvas来生成海报,下面为选择4和2张图片的海报截图;
![](https://img-blog.csdnimg.cn/20210306160137671.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQ1MjM2NTEw,size_16,color_FFFFFF,t_70)
![](https://img-blog.csdnimg.cn/20210306163354167.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQ1MjM2NTEw,size_16,color_FFFFFF,t_70)
开发过程中学到的东西
1、自动闭合及非零环绕原则
在绘制气泡和海报的时候需要绘制圆角,网上有查找到相关的方案但是并不满意,后来了解到canvas绘制arc会首尾相连,即第一个arc的终点会连接第二个arc的起点(在没有使用moveTo的情况,使用moveTO已经把画笔移动走了,当然不会连接啦),这样只需要绘制四个角的圆弧就可以啦;
_drawCanvasBoard (ctx) {
// 绘制背景
ctx.save()
ctx.rect(0, 0, this.canvasWidth, this.canvasHeight)
ctx.setFillStyle('#e6e6e6')
ctx.fill()
ctx.restore()
const x = this.margin,
y = this.margin,
w = this.canvasWidth - this.margin * 2,
h = this.canvasHeight - this.margin * 2,
r = 10;
ctx.beginPath()
ctx.arc(x+r, y+r, r, Math.PI, Math.PI * 1.5)
ctx.arc(w+x-r, y+r, r, -0.5 * Math.PI, 0)
ctx.arc(w+x-r, y+h-r, r, 0, 0.5 * Math.PI)
ctx.arc(x+ , y+h-r, r, 0.5 * Math.PI, Math.PI)
ctx.closePath()
ctx.setFillStyle('#efefef')
ctx.fill()
}
drawBubble (x, y, w, h, r, ctx) {
// 绘制气泡
ctx.beginPath()
ctx.arc(x, y + r, r, Math.PI, Math.PI * 1.5)
ctx.arc(w+x-r, y+r, r, -0.5 * Math.PI, 0)
ctx.arc(w+x-r, y+h-r, r, 0, 0.5 * Math.PI)
ctx.arc(x, y+h-r, r, 0.5 * Math.PI, Math.PI)
ctx.arc(x-r-4, y+0.6*h, 4, 0, Math.PI * 1.7, true)
ctx.arc(x-r-6, y+0.3*h, 3, Math.PI * 0.5, Math.PI)
ctx.arc(x-r-2, y+0.25*h, 2, Math.PI * 0.4, Math.PI * 2, true)
ctx.closePath()
ctx.setFillStyle('#fff')
ctx.fill()
ctx.setFillStyle('#333')
ctx.save()
ctx.beginPath()
ctx.setFontSize('12')
ctx.fillText(this.userTel, x, y + r + h/4 - 4)
ctx.restore()
ctx.save()
ctx.setFontSize('13')
ctx.fillText('这是我发现的超值好物~', x, y+r+h/2 + 4)
ctx.restore()
},
2、隐藏超出的字
计算字的宽度和可绘制区域的宽度,多余的截取掉再拼接上’…’;
measureText (text, ctx) {
const width = this.contentWidth - 2 * this.padding - 30
while(ctx.measureText(text).width > width) {
text = text.substring(0, Math.floor(text.length * 0.8)) + '...'
}
return text
}
3、缓存图片资源
4、文字换行
同理需要计算文字宽度与可绘制区域的宽度,截取后绘制。参考了文章canvas文本绘制自动换行、字间距、竖排等实现
总结
微信扫码体验