// pages/downZS/index.js Page({ /** * 页面的初始数据 */ data: { ls_url: "", selectIndex: 0, users: [{ name: "李勇利" }, { name: "张云翔" }, ] }, systemInfo: wx.getSystemInfoSync(), /** * 生命周期函数--监听页面加载 */ onLoad(options) { // 获取远程图片 wx.showLoading({ title: '加载中', mask: true }) wx.getImageInfo({ src: "https://cxzx.smcic.net/topic/tool/img/%E5%B0%91%E5%84%BF%E4%B9%A6%E7%94%BB%E5%A4%A7%E8%B5%9B/6.jpg", }).then((res) => { const { width, height, path } = res; const users = JSON.parse(JSON.stringify(this.data.users)); const canvas = wx.createOffscreenCanvas({ type: '2d', width, height }); const ctx = canvas.getContext('2d'); const img = canvas.createImage(); img.onload = () => { for (let i = 0; i < users.length; i++) { const v = users[i]; ctx.drawImage(img, 0, 0, width, height); ctx.fillStyle = "#000000"; ctx.font = (width / 20) + 'px 微软雅黑'; ctx.fillText(v.name, width * 0.18, height * 0.4); wx.canvasToTempFilePath({ x: 0, y: 0, width, height, destWidth: width, destHeight: height, canvas, fileType: 'jpg', success: res => { v.url = res.tempFilePath if (i === users.length - 1) { this.setData({ ls_url: users, }); } }, complete: () => { wx.hideLoading(); } }) } } img.onerror = () => wx.hideLoading(); img.src = path // 要加载的图片 url }).catch(err => { wx.hideLoading(); }); }, change(e) { this.setData({ selectIndex: e.detail.current }) }, download() { if (!this.data.ls_url[this.data.selectIndex] || !this.data.ls_url[this.data.selectIndex].url) return wx.saveImageToPhotosAlbum({ filePath: this.data.ls_url[this.data.selectIndex].url, // 使用下载得到的临时文件路径 success: function (saveRes) { wx.showToast({ title: '已保存至相册', icon: 'success', duration: 2000 }); }, fail: function (err) { if (err.errMsg === 'saveImageToPhotosAlbum:fail:auth denied') { wx.showModal({ title: '保存失败', content: '请前往设置页面授权保存图片到相册', showCancel: false, success: function (modalRes) { wx.openSetting({ withSubscriptions: true, success: function (res) { if (res.authSetting['scope.writePhotosAlbum']) { // 用户重新授权后,再次尝试保存图片 wx.saveImageToPhotosAlbum({ filePath: res.tempFilePath, success: function (saveRes) { wx.showToast({ title: '保存成功', icon: 'success', duration: 2000 }); }, fail: function (err) { wx.showToast({ title: '保存失败', icon: 'none', duration: 2000 }); } }); } }, fail: function (err) { wx.showToast({ title: '打开设置页面失败', icon: 'none', duration: 2000 }); } }); } }); } else { wx.showToast({ title: '保存失败', icon: 'none', duration: 2000 }); } } }); }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady() { }, /** * 生命周期函数--监听页面显示 */ onShow() { }, /** * 生命周期函数--监听页面隐藏 */ onHide() { }, /** * 生命周期函数--监听页面卸载 */ onUnload() { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh() { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom() { }, /** * 用户点击右上角分享 */ onShareAppMessage() { return { title: __wxConfig.accountInfo.nickname, path: "/pages/index/index" } } })