微信小程序 获取经纬度、图片加水印上传

  1. 微信小程序获取经纬度
  const queryAuthority = () => {
    // 可以通过 Taro.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
    Taro.getSetting({
      success: function (res) {
        if (!res.authSetting["scope.userLocation"]) {
          Taro.authorize({
            scope: "scope.userLocation",
            success: function () {
              // 用户已经同意小程序使用录音功能,后续调用 Taro.startRecord 接口不会弹窗询问
              queryLocation();
            },
            fail: () => {
              rejectModal();
            },
          });
        } else {
          queryLocation();
        }
      },
    });
  };
  
  const rejectModal = () => {
    Taro.switchTab({
      url: `../workOrder/index`,
    });
    Taro.showModal({
      title: "提示",
      content: "请开启定位权限后重试",
      success: () => {
        Taro.openSetting();
      },
    });
  };

  const queryLocation = () => {
    Taro.getLocation({
      type: "gcj02",
      success(res) {
        changeLocation(res);
      },
      fail: (e) => {
        console.log(e);
      },
    });
  };
  1. 微信小程序图片加水印上传
    代码中的canvasNode和canvasCtx获取方法请移步 小程序Canvas官方新版API实战
/**
 * 图片加水印上传原理是:把图片画到canvas上,加完水印,再保存成图片上传
 * 因此是按屏幕大小重绘,如果是高清的图片,清晰度会下降。暂时没有解决办法
 */
const addWatermark = async (url: string) => {
  if (!location.latitude) {
    return url;
  }
  return new Promise(async (resolve) => {
    const imgInfo = await Taro.getImageInfo({ src: url });
    let width = imgInfo.width;
    let height = imgInfo.height;
    const systemInfo = Taro.getSystemInfoSync();
    const { windowWidth: screenWidth, pixelRatio: dpr } = systemInfo;
    height = screenWidth * height /  width;
    width = screenWidth;// 计算等比例变换后的图片宽高
    canvasNode.width = width * dpr;
    canvasNode.height = height * dpr;
    canvasCtx.scale(dpr, dpr);// canvas默认不设置像素比,需手动设置
    // 以下流程:建容器,填充地址,画图片,加水印信息,转临时路径
    const Img = canvasNode.createImage();
    Img.src = url;
    Img.onload = async () => {
      canvasCtx.drawImage(Img, 0, 0, width, height);
      canvasCtx.fillStyle = "white";
      canvasCtx.font = 9;
      canvasCtx.fillText(moment().format("YYYY/MM/DD HH:mm:ss"), 0, 10);
      canvasCtx.fillText(location.address, 0, 20);
      Taro.canvasToTempFilePath({
        canvas: canvasNode,
        success: function (res) {
          resolve(res.tempFilePath);
        },
      });
    };
  });
};

// url:微信小程序图片临时路径,myUrl:添加水印后的图片临时路径
const myUrl = await addWatermark(url);
// 以下是由前端上传图片的代码 (diss万恶的大前端)
const imgBuffer = fileSystemManager.readFileSync(url);
const suffix = url.slice(url.lastIndexOf(".") + 1);
const rs = await Taro.request({
  url: data.payload,
  header: {
    "content-type": fileType[suffix],
  },
  method: "PUT",
  data: imgBuffer,
});
if (rs.statusCode === 200) {
  fileObj.file.path = data.payload.substr(0, data.payload.indexOf("?"));
  oldFiles.push(fileObj);
} else {
  error = rs;
}

你可能感兴趣的:(小程序,微信小程序,typescript,前端)