支付宝小程序使用canvas保存图片

2,014 阅读1分钟

速通

//canvas生成路径Api 
//Api说明文档:https://opendocs.alipay.com/mini/api/rod3ti
ctx.toTempFilePath({
  success(e) {
    //保存图片Api
    //Api说明文档:https://opendocs.alipay.com/mini/api/izfoiz
    my.saveImage({
      url: e.apFilePath,
      showActionSheet: true,
      success: () => {
        my.alert({
          title: '保存成功',
        });
      },
    });
  },
})

index.axml

<canvas id="shareBox" />
<button type="primary" onTap="saveImg">操作</button>

index.js

let scale = ''
my.getSystemInfo({
  success: (res) => {
    scale = res.windowWidth / 750;
  }
})
const ctx = my.createCanvasContext('shareBox');

Page({
  onLoad(query) {
    // 页面加载
    console.info(`Page onLoad with query: ${JSON.stringify(query)}`);
  },
  onReady() {
    // 页面加载完成
    this.drawShareImage();
  },
  drawShareImage(){
    let option = {
      imgUrl : 'img.png'
    };
    //图片越大越清晰,所有我这是基于原尺寸*2
    ctx.drawImage(option.imgUrl,0, 0, (650*2) * scale, (1125*2) * scale);
    //在上面绘画文字 this.drawNormalText(ctx, "恭喜您成为", 1, 1, 12, '#000000', 'middle');
    ctx.draw()
  },
  drawNormalText(ctx, str, x, y, font, style, baseLine) {
    //因为上面我尺寸*2了,绘画文字的数值也需要*2
    ctx.setFontSize((font*2) * scale);
    ctx.setFillStyle(style);
    ctx.setTextBaseline(baseLine);
    ctx.fillText(str, (x*2) * scale, (y*2) * scale);
  },
  saveImg(){
    ctx.toTempFilePath({//canvas生成路径Api
      success(e) {
        my.saveImage({//保存图片Api
          url: e.apFilePath,
          showActionSheet: true,
          success: () => {
            my.alert({
              title: '保存成功',
            });
          },
        });
      },
    });
  }
});