前言
最近发现好多好友头像挂上了小挂件,感觉还挺好玩,顺手也做了一个,水一篇文。
思路
其实整个功能非常简单,主要包含一个头像展示区域、选择头像按钮,和挂件区、最后利用canvas合成头像。
用户头像获取
由于微信getUserInfo的限制,现在只能改成button open type方式获取
<button class="btn btn-my" open-type="chooseAvatar" bindchooseavatar="onChooseAvatar">
选择头像
</button>
获取挂件
首先准备好对应的挂件素材图片,然后加入主题panel即可
<view class="material-scroll-box">
<swiper class="scroll-view" scroll-x scroll-with-animation indicator-dots>
<swiper-item class="scroll-item-wrap" wx:for="{{ornamentPic[selectType]}}" wx:key="index">
<t-grid class="scroll-grid" column="{{4}}">
<t-grid-item wx:for="{{item}}" wx:key="id" image="{{item.url}}" data-img="{{item.url}}" bindtap="onChoosePendant" />
</t-grid>
</swiper-item>
</swiper>
</view>
设置挂件在头像内可移动
很简单,只要在头像预览区域设置一个move area 即可
<movable-area class="movable-area">
<movable-view class="movable-block" bindchange="onMovableChange" direction="all">
<view class="pendant-img">
<image id='pendantImg' src="{{pendant.img}}" mode="widthFix" width="height: {{pendant.height}}" />
</view>
</movable-view>
</movable-area>
合成图片
这边使用小程序painter作为canvas合成插件,配置好后即可
if (isPosterPainting) return
const [businessCard] = await Promise.all([require.async("/painterConfig.js")])
const paletteOption = {
avatarImg: defaultAvatar.replace("./", "/"),
pendantImg: pendant.img.replace("../../../", "/"),
pendantX: pendant.x,
pendantY: pendant.y,
pendantWidth: pendant.width,
pendantHeight: pendant.height,
}
this.setData({
isPosterPainting: true,
paintPallette: new businessCard.default().palette(paletteOption),
})
// 等待绘制海报
let promise = new Promise((resolve, reject) => {
this.painterCallBack = resolve
})
promise.then((imgUrl) => {
this.setData({
generateAvatar: imgUrl,
isPosterPainting: false,
})