效果如下图:
子组件代码:
<template name="canvas-avatar">
<canvas :id="canvasId" :canvas-id="canvasId" :style="styleProp" :data-text="text"></canvas>
</template>
<script>
export default {
name: "canvas-avatar",
props: {
styleProp: {
type: String,
default: ''
},
text: {
type: String,
default: ''
},
canvasId: {
type: String,
default: ''
},
bgColor: {
type: String,
default: ''
}
},
data() {
return {
isShowToTop: true
}
},
mounted(){
let ctx = uni.createCanvasContext(this.canvasId, this)
// 1.填充背景色
ctx.setFillStyle(this.bgColor); // 背景颜色,默认白色
ctx.fillRect(0, 0, 40, 40) // fillRect(x,y,宽度,高度)
// 2.绘制文字
ctx.setFontSize(16) // 字号
ctx.setFillStyle('#fff') // 字体颜色
ctx.fillText(this.text, 12,24); // (文字,x,y)
// 3.绘制
ctx.draw()
},
methods: {
}
}
</script>
<style scoped lang="scss"></style>
父组件相关代码如下:
<view class="menu-item" v-for="(item,index) in menuList" :key="index">
<view class="menu-icon">
<canvas-avatar :style-prop="'width: 40px;height:40px;'" :canvasId="'myCanvas'+index" :text="(item.name).substring(0,1)" :bg-color="item.bgColor"></canvas-avatar>
</view>
<view class="menu-name">{{item.name}}</view>
</view>
list数据结构如下:
menuList:[
{
id:0,
name:'湘菜',
bgColor:'#FF5B5B'
},
{
id:1,
name:'杭帮菜',
bgColor:'#31ABFF'
},
{
id:2,
name:'川菜',
bgColor:'#FF356B'
},
{
id:3,
name:'新疆菜',
bgColor:'#0DCA0B'
},
{
id:4,
name:'东北菜',
bgColor:'#42D532'
},
{
id:5,
name:'豫菜',
bgColor:'#18A2FF'
},
{
id:6,
name:'泰国菜',
bgColor:'#2BE6AC'
},
{
id:7,
name:'北京菜',
bgColor:'#FF812F'
},
{
id:8,
name:'新加坡菜',
bgColor:'#FF5E88'
},
{
id:9,
name:'陕西菜',
bgColor:'#FFBA3A'
}
],
背景图我这是是通过父标签设置border-radius、overflow属性来超出隐藏将一个矩形变成圆形的
注意:
问题1:遍历绘制全绘制成最后一个了
解决方案:因为要遍历绘制canvas,而绘制canvas又是根据canvas-id来绘制的,所以在子组件内我们不能把canvas-id写死,而是通过父组件传参的形式生成不同canvas-id的canvas节点,否则,图中的效果就会变成全是“陕”。