功能⑨⼩程序使⽤canvas制作海报并转换为图⽚保存总结
⽂档
1. 使⽤wx.getImageInfo()将头像+⼆维码转临时路径
beforCreateImage() {
let that = this
src: that.data.avatarUrl,
success: res => {
const avatarUrl = res.path
src: that.data.userInfo.showPic,
success: res2 => {
const qrUrl = res2.path
const text = that.data.userInfo.name + that.data.userInfo.phone
},
fail: err => console.log(33, err)
})
新年搞笑祝福语},
fail: err => console.log(22, err)
})
}
2. 绘制海报 -- ⽤到的路径都是本地路径
<!-- 页⾯中不需要展⽰海报 -->
<canvas canvas-id="myCanvas" ></canvas>
createImage(avatarUrl, qrUrl, text) {
let that = this
// 创建canvas的绘图上下⽂ CanvasContext 对象
const ctx = wx.createCanvasContext('myCanvas')
// 绘制背景 (图⽚地址, x, y, width, height)
ctx.drawImage('/img/qr_code_bg.png', 0, 0, 300, 400)
// 绘制头像:注意裁剪区域与绘制图⽚时的定位+⼤⼩关系
ctx.save() // 保存当前绘图上下⽂
ctx.beginPath() // 开始创建⼀个路径
// ctx.arc(x, y, r, sAngle, eAngle, 弧度⽅向是否逆时针)
ctx.arc(80/2+110, 80/2+50, 40, 0, 2 * Math.PI, false)// 画⼀个圆形裁剪区域
ctx.clip() // 裁剪教师节文案简短十字
ctx.drawImage(avatarUrl, 110, 50, 80, 80); // 绘制图⽚
// 绘制⽂本
ctx.setFillStyle('#000') // ⽂字颜⾊:默认⿊⾊
ctx.font = 'normal bold 18px sans-serif';
// ctx.setFontSize(18)
ctx.fillText(text, 70, 160) // 绘制⽂本
/
/ 绘制⼆维码
ctx.save() // 保存当前绘图上下⽂
ctx.beginPath() // 开始创建⼀个路径
ctx.arc(120/2+90, 120/2+186, 60, 0, 2 * Math.PI, false) // 画⼀个圆形裁剪区域
ctx.clip() // 裁剪
ctx.drawImage(qrUrl, 90, 186, 120, 120); // 绘制图⽚
// 绘制⽂本
ctx.setFillStyle('#000')//⽂字颜⾊:默认⿊⾊
ctx.font = 'normal normal 14px sans-serif';
ctx.fillText('⼯作职业培训⼀站式服务平台', 50, 350)//绘制⽂本
ctx.draw()
}
3. 点击保存,使⽤wx.canvasToTempFilePath()将canvas转为图⽚
saveHaiBaoImage() {
let that = this李东健主演的电视剧
//将⽣成好的图⽚保存到本地,需要延迟⼀会,绘制期间耗时
setTimeout(() => {
wx.canvasToTempFilePath({
canvasId: 'myCanvas',
success: res => {
var tempFilePath = pFilePath;
that.shareImage(tempFilePath) // 保存图⽚
},
fail:res => {
console.log(res);
}
});
}, 100);
}
4. 使⽤wx.saveImageToPhotosAlbum()保存图⽚
async shareImage(url) {
let that = this
/
/ 验证⽤户是否拥有保存到相册的权限
success: res => {
if (res.authSetting['scope.writePhotosAlbum']) {
// ⽤户已授权
that.saveImage(url);
} else if (res.authSetting['scope.writePhotosAlbum'] !== undefined){
// ⽤户⾸次进⼊还未调起权限相关接⼝
that.openSetting();
} else {
// ⽤户⾸次进⼊
that.saveImage(url);
}
},
fail: () => {
}
})
},
// 需要授权
openSetting() {
wx.showModal({
title: '提⽰',
content: '请先授权同意保存图⽚到相册',
confirmText: '确定授权',
success: res => {
来玩吧千正明
if (firm) {
wx.openSetting({
fail: () => {
});
杨丞琳王子}
}
})
},
// 保存图⽚
saveImage(url) {
let that = this
wx.saveImageToPhotosAlbum({
filePath: url,
英语阅读理解技巧
success: () => {
this.setData({
isShow: false
})
},
fail: () => {
}
})
},