注意由于微信小程序的安全限制,我们无法直接加载外部图片。因此,在实际应用中,需要先将头像图片下载到本地,然后再将它们加载到画布上。另外,如果头像图片数量不足9张,需要根据实际情况调整九宫格的排列方式。
基本使用
1.创建一个canvas画布,并设置画布的大小和样式。
<template>
<view class="box">
<canvas canvas-id="avatar" style="width:300rpx;height:300rpx" ></canvas>
</view>
</template>
2.获取所有用户的头像图片地址,并将它们存储在一个数组中
// 头像图片数组
const avatarUrls = [
'../../static/1.jpg',
'../../static/2.jpg',
'../../static/3.jpg',
'../../static/4.jpg',
'../../static/5.jpg',
'../../static/6.jpg',
'../../static/7.jpg',
'../../static/8.jpg',
'../../static/9.jpg',
];
3.将头像图片加载到画布上,并按照九宫格的方式排列。可以使用for循环来遍历头像图片数组,并根据每个头像图片的位置计算出它在画布上的坐标
4.将所有头像图片绘制到画布上,并保存为一张新的图片
<script>
export default {
data() {
return {
}
},
onLoad() {
},
methods: {
},
mounted() {
const ctx = uni.createCanvasContext('avatar', this);
// 头像图片数组
const avatarUrls = [
'../../static/1.jpg',
'../../static/2.jpg',
'../../static/3.jpg',
'../../static/4.jpg',
'../../static/5.jpg',
'../../static/6.jpg',
'../../static/7.jpg',
'../../static/8.jpg',
'../../static/9.jpg',
];
// 计算每个头像图片在画布上的坐标
const avatarSize = 100;
const padding = 1;//图片之间的边距
for (let i = 0; i < avatarUrls.length; i++) {
const row = Math.floor(i / 3);
const col = i % 3;
const x = col * (avatarSize + padding);
const y = row * (avatarSize + padding);
ctx.drawImage(avatarUrls[i], x, y, avatarSize, avatarSize);
}
// 将所有头像图片绘制到画布上,并保存为一张新的图片
ctx.draw(false, () => {
uni.canvasToTempFilePath({
canvasId: 'avatar',
success: (res) => {
console.log(res.tempFilePath);
},
}, this);
});
},
}
</script>
设置整体圆角
<template>
<view class="box">
<canvas canvas-id="avatar" class="avatar-canvas" ></canvas>
</view>
</template>
<script>
export default {
data() {
return {
}
},
onLoad() {
},
methods: {
},
mounted() {
const ctx = uni.createCanvasContext('avatar', this);
// 头像图片数组
const avatarUrls = [
'../../static/1.jpg',
'../../static/2.jpg',
'../../static/3.jpg',
'../../static/4.jpg',
'../../static/5.jpg',
'../../static/6.jpg',
'../../static/7.jpg',
'../../static/8.jpg',
'../../static/9.jpg',
];
// 计算每个头像图片在画布上的坐标
const avatarSize = 100;
const padding = 1;//图片之间的边距
for (let i = 0; i < avatarUrls.length; i++) {
const row = Math.floor(i / 3);
const col = i % 3;
const x = col * (avatarSize + padding);
const y = row * (avatarSize + padding);
ctx.drawImage(avatarUrls[i], x, y, avatarSize, avatarSize);
}
// 将所有头像图片绘制到画布上,并保存为一张新的图片
ctx.draw(false, () => {
uni.canvasToTempFilePath({
canvasId: 'avatar',
success: (res) => {
console.log(res.tempFilePath);
},
}, this);
});
},
}
</script>
<style>
.box{
width: 300px;
height: 300px;
border-radius: 50rpx;
overflow: hidden;
}
.avatar-canvas{
width: 100%;
height: 100%;
background-color: #fff;
}
</style>