- <view class="img_" style="width: 100%;">
- <canvas type="2d" id="canvasId" style="width: 100%;height: 100%" >canvas>
- <button style="margin: auto;width: 70%;margin-top: 10px;" bindtap="saves">保存图片button>
- view>
样式可以根据自己需求自行调整
- //写在接口成功回调中
- const fs = wx.getFileSystemManager();
- var codeimg = wx.env.USER_DATA_PATH + '/' + '.jpg';
- fs.writeFile({
- filePath: codeimg,
- data: res.data.slice(22), // code就是接口返回的base64数据(分割掉前面的data:image/png;base64,)
- encoding: 'base64',
- success: () => {
- // console.log(codeimg);
-
- wx.createSelectorQuery().select('#canvasId').fields({
- node: true,
- size: true
- })
- .exec((res) => {
- console.log(res);
- let ctx = res[0].node.getContext('2d'); //getContext返回Canvas 的绘图上下文
- let canvas = res[0].node;
- const bg = canvas.createImage();
- //背景图片,可以不进行设置
- const image = canvas.createImage();
- // 图片高清化
- const dpr = wx.getSystemInfoSync().pixelRatio;
- res[0].node.width = res[0].node.width * dpr;
- res[0].node.height = res[0].node.height * dpr;
- // 设置背景图片src
- image.src = 'https://pic.imgdb.cn/item/647d31011ddac507cc160e75.jpg'
- bg.src = codeimg;
- image.onload = function () {
- ctx.drawImage(image, 0, 0, 900, 440)
- ctx.drawImage(bg, 240, 210, 430, 160);
-
- }
- // 将图片保存需要的实例,不写保存可以删除
- that.setData({
- ctx:canvas
- })
- })
- // 检查用户是否已经授权
- wx.getSetting({
- success: (res) => {
- if (!res.authSetting['scope.writePhotosAlbum']) {
- // 如果用户未授权,则向用户请求授权
- wx.authorize({
- scope: 'scope.writePhotosAlbum',
- success: () => {
- console.log('授权成功')
- },
- fail: () => {
- console.log('授权失败')
- }
- })
- } else {
- console.log('已经授权')
- }
- }
- })
- // 保存图片
- saves() {
- let _this = this;
- wx.canvasToTempFilePath({
- // 把画布转化成临时文件
- x: 0,
- y: 0,
- width: 380, // 截取的画布的宽
- height: 600, // 截取的画布的高
- destWidth: 380, // 保存成的画布宽度
- destHeight: 600, // 保存成的画布高度
- fileType: 'jpg', // 保存成的文件类型
- quality: 1, // 图片质量
- //如果图片不是2D的话,就需要使用canvasId属性,详情请查看微信小程序官方文档
- canvas:_this.data.ctx, // 画布实例
- success(res) {
- // 2-保存图片至相册
- wx.saveImageToPhotosAlbum({
- // 存成图片至手机
- filePath: res.tempFilePath,
- success(res2) {
- wx.hideLoading();
- wx.showToast({
- title: '保存成功',
- duration: 2000
- });
- },
- fail(res3) {
- if (res3.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
- wx.showToast({
- title: '保存失败,稍后再试',
- duration: 2000,
- icon: 'none'
- });
- wx.hideLoading();
- } else {
- wx.showToast({
- title: '保存失败,稍后再试',
- duration: 2000,
- icon: 'none'
- });
- wx.hideLoading();
- }
- }
- });
- },
- fail(err) {
- console.log(err);
-
- wx.showToast({
- title: '保存失败,稍后再试',
- duration: 2000,
- icon: 'none'
- });
- wx.hideLoading();
- }
- });
- }