uniapp Canvas使用

注意使用canvas 若是网络资源,要用getImageInfo转换成本地路径。

   getImageInfo(src) {
    return new Promise((resolve, reject) => {
      uni.getImageInfo({
        src,
        success: (res) => resolve(res),
        fail: (res) => reject(res),
      });
    });
  }


async img(userImage: string, userNickname: string) {
    if (!this.shareImage) {
      return uni.showToast({ title: "请稍后重试", icon: "error" });
    }

    let that = this;

    //this.getImageInfo将网络资源变成本地地址
    const res1: { [key: string]: any } = await this.getImageInfo(userImage);
    const res2: { [key: string]: any } = await this.getImageInfo(
      this.shareImage
    );
    

    const system = uni.getSystemInfoSync();
    var ctx = uni.createCanvasContext("firstCanvas"); // 使用画布创建上下文 图片

    // 设置图片坐标及大小,括号里面的分别是(图片路径,x坐标,y坐标,width,height)
    ctx.drawImage(
      res2.path,
      0,
      0,
      system.windowWidth * 0.8,
      system.windowHeight * 0.6
    );

    ctx.setFontSize(12); //设置字体大小,默认10

    ctx.setTextAlign("center"); //文本水平居中
    ctx.fillText(userNickname, 95, system.windowHeight * 0.6 - 35); //文字内容、x坐标,y坐标

    ctx.save(); // 对当前区域保存
    ctx.beginPath(); // 开始新的区域
    
    //画x轴圆心点 画y轴圆心点 画圆的半径
    ctx.arc(40, system.windowHeight * 0.6 - 40, 20, 0, Math.PI * 2, false);

    ctx.clip(); // 从画布上裁剪出这个圆形
    ctx.drawImage(res1.path, 20, system.windowHeight * 0.6 - 60, 40, 40);
    ctx.restore(); // 恢复
    ctx.save(); //保存
    ctx.draw(); //绘制

  }

你可能感兴趣的:(uni-app,小程序)