本篇文章带大家跟风做一个虎年春节头像制作小程序,获取微信头像,选择头像边框,即可合成不同的虎年春节头像,希望对大家有所帮助!

马上就到春节了,今天看到有网友分享了网页版的虎年头像制作工具,感觉很不错,正好打算做个小程序练手没啥主题,那就用这个试试吧。
先上最终效果图:

说下实现流程
第一步:先获取到当前微信的头像图片,主要代码如下,注意默认获取到的头像图片不是高清的,需要先转换成高清图片,避免生成之后很模糊。
getuserprofile(e) {
console.log(e)
let that = this;
wx.getuserprofile({
desc: '仅用于生成头像使用',
success: (res) => {
var url = res.userinfo.avatarurl;
while (!isnan(parseint(url.substring(url.length - 1, url.length)))) {
url = url.substring(0, url.length - 1)
}
url = url.substring(0, url.length - 1) + "/0";
res.userinfo.avatarurl = url;
console.log(json.stringify(res.userinfo));
that.setdata({
userinfo: res.userinfo,
hasuserinfo: true
})
that.drawimg();
}
});
},第二步:合成头像,把素材图片和第一步获取到的头像图片,获取到本地文件,然后利用小程序的cavas组件进行合成。
drawimg() {
let that = this;
wx.showloading({
title: '生成头像中...',
})
let promise1 = new promise(function (resolve, reject) {
wx.getimageinfo({
src: that.data.userinfo.avatarurl,
success: function (res) {
resolve(res);
}
})
});
var mask_id = that.data.now_mask;
let promise2 = new promise(function (resolve, reject) {
wx.getimageinfo({
src: `../../assets/img/mask0${mask_id}.png`,
success: function (res) {
console.log(res)
resolve(res);
}
})
});
promise.all([
promise1, promise2
]).then(res => {
console.log(res)
var windowwidth = wx.getsysteminfosync().windowwidth
var context = wx.createcanvascontext('myavatar');
var size = windowwidth /750 * 500
// var size = 500
context.drawimage(res[0].path, 0, 0, size, size);
context.draw(true)
context.save();
context.drawimage('../../'+res[1].path, 0, 0, size, size);
context.draw(true)
context.save();
})
wx.hideloading()
},第三步:下载合成的图片到本地相册。
canvastotempfile(){
if(!this.data.userinfo){
wx.showmodal({
title: '温馨提示',
content: '请先点击上方获取微信头像',
showcancel: false,
})
return
}
var windowwidth = wx.getsysteminfosync().windowwidth
var size = 500
// var dpr = 750 / windowwidth
wx.canvastotempfilepath({
x: 0,
y: 0,
height: size,
width: size,
canvasid: 'myavatar',
success: (res) => {
wx.saveimagetophotosalbum({
filepath: res.tempfilepath,
success: result => {
wx.hideloading();
wx.showmodal({
content: '图片已保存到相册,请前往微信去设置哟!',
showcancel: false,
success: function(res) {
if (res.confirm) {
console.log('用户点击确定');
}
}
})
}, fail(e) {
wx.hideloading();
console.log("err:" + e);
}
})
}
});
},这样就实现了主要的功能了。
最后放上小程序码,欢迎大家扫码体验一下:

最后 当前项目已开源:https://github.com/hackun666/new-year-face
祝大家春节快乐,虎年大吉!
原文地址:https://juejin.cn/post/7057807283463389191
作者:hackun
【相关学习推荐:小程序开发教程】
以上就是带你开发一个虎年春节头像生成小程序的详细内容,更多请关注代码网其它相关文章!
发表评论