原生微信小程序常见 API 使用案例

176 阅读2分钟

关键词:demo collections 微信小程序

demo 源码:gitee.com/huakangkane…

Canvas

canvas 文档

重要:canvas 基础使用

结合 onShareAppMessage 使用demo:

<style>
/* wxss */
.cantSee {
  width: 320px;
  height: 256px;
}
</style>

<!-- wxml -->
<canvas class="cantSee" type="2d" ></canvas>
<button open-type="share">分享</button>

<!-- js -->
<script>
Page({
  data: {
    imgPath: ''
  },
  onShow() {
    this.draw()
  },
  draw() {
    // 获取元素
    wx.createSelectorQuery()
      .select('.cantSee')
      .fields({ node: true, size: true })
      .exec(this.initImagePath.bind(this));
  },
  initImagePath(list) {
    const dpr = wx.getSystemInfoSync().pixelRatio;
    const item = list[0];
    const canvas = item.node;
    const context = canvas.getContext('2d');
    const { width } = item;
    const { height } = item;
    canvas.width = width * dpr;
    canvas.height = height * dpr;
    context.scale(dpr, dpr);
    // 设置背景/方块
    context.fillStyle = 'green';
    context.fillRect(0, 0, width, height);
    // 画圆
    context.fillStyle = 'blue';
    context.beginPath();
    context.arc(550, 300, 400, 0, Math.PI * 10);
    context.strokeStyle = 'rgba(1,1,1,0)';
    context.fill();
    context.stroke();
    // 设置边框
    context.strokeStyle = '#666';
    context.strokeRect(0, 0, width, height);
    // 写字
    context.fillStyle = '#fff';
    context.font = '70px "Fira Sans"';
    context.textAlign = 'center';
    context.fillText('测试', 160, 120);
    // 再写一个
    context.font = '20px "Fira Sans"';
    context.textAlign = 'center';
    context.fillText('测试', 160, 190);
    context.restore();
    const _this = this;
    // 保存为图片
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width,
      height,
      canvas,
      success: (res) => {
        _this.setData({
          imgPath: res.tempFilePath
        })
      },
    });
  },
  // 点击分享
  onShareAppMessage() {
    const { imgPath } = this.data
    return {
      title: `自定义标题`,
      path: `/pages/index/index`,
      imageUrl: imgPath,
      success(res) {
        // 转发成功之后的回调
        if (res.errMsg === 'shareAppMessage:ok') {
          // ...
        }
      },
      fail(res) {
        // 转发失败之后的回调
        if (res.errMsg === 'shareAppMessage:fail cancel') {
          // 用户取消转发
        } else if (res.errMsg === 'shareAppMessage:fail') {
          // 转发失败,其中 detail message 为详细失败信息
        }
      }
    }
  },
})
</script>

效果:

image.png

上传文件/图片

实现上传功能通常可以直接使用 UI 框架自带的上传组件

如果需求比较简单,或者定制化程度比较高。也可以自己简单实现一个:

wx.chooseMedia 选择文件

wx.uploadFile 上传

Page({
  data: {
    imgUrl: null
  },
  // 上传图片
  async toModifyImage() {
    const _this = this;
    try {
      const tempFilePath = await new Promise((resolve, reject) => {
        wx.chooseMedia({
          count: 1,
          mediaType: 'image',
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            const { tempFilePath, size } = res.tempFiles[0];
            if (size <= 10485760) {
              resolve(tempFilePath);
            } else {
              reject({ errMsg: '图片大小超出限制,请重新上传' });
            }
          },
          fail: (err) => reject(err),
        });
      });
      // 上传
      wx.uploadFile({
        url: `/api/uploadFile`, // 上传接口
        filePath: tempFilePath,
        header: { Authorization: wx.getStorageSync('token') },
        name: 'file',
        success({ statusCode, data }) {
          if (statusCode === 200) {
            const result = JSON.parse(data);
            const { imgUrl } = result.data;
            _this.setData({ imgUrl });
          }
        },
      });
    } catch (error) {
      if (error.errMsg === 'chooseImage:fail cancel') return;
      console.log('上传图片报错', error);
    }
  },
})

地图组件/导航

map 地图组件

腾讯位置服务

腾讯位置服务 微信小程序中使用API

wx.chooseLocation

最简单的就是直接把Map组件塞进去,增加功能就添加对应的插件服务,其实没什么难度。按照文档一步步执行就能出效果。下面是基于官方文档写的简单的业务需求:展示位置,点击按钮进行导航。

// app.json
{
  // ...
  "permission": {
    "scope.userLocation": {
      "desc": "你的位置信息将用于小程序定位"
    }
  },
  "requiredPrivateInfos": [
    "chooseLocation",
    "getLocation"
  ],
  "requiredBackgroundModes": [
    "location"
  ],
  "sitemapLocation": "sitemap.json",
  // 微信路线规划插件
  "plugins": {
    "routePlan": {
      "version": "1.0.18",
      "provider": "wx50b5593e81dd937a"
    }
  }
}

<view class="map-wrap">
  <map
    id="mapId"
    class="map"
    subkey="{{subkey}}"
    latitude="{{latitude}}"
    longitude="{{longitude}}"
    bindmarkertap="onMarkerTap"
  ></map>
</view>
<view class="btn-wrap">
  <button bindtap="onAppNav">微信导航(推荐)</button>
  <button bindtap="onPluginNav">小程序导航</button>
</view>

<script>
Page({
  data: {
    latitude: 23.099994,
    longitude: 113.324520,
    // 申请的腾讯位置服务key
    subkey: ''
  },
  // 聚合图层示例代码 https://developers.weixin.qq.com/miniprogram/dev/component/map.html

  // app导航
  onAppNav() {
    const { detail, latitude, longitude } = this.data;
    wx.openLocation({
      name: detail,
      latitude: +latitude,
      longitude: +longitude,
    });
  },
  // 小程序导航
  onPluginNav() {
    const { subkey, detail, latitude, longitude } = this.data;
    const referer = '小程序'; // 调用插件的app的名称
    const endPoint = JSON.stringify({
      //终点
      name: detail,
      latitude: +latitude,
      longitude: +longitude,
    });
    wx.navigateTo({
      url: `plugin://routePlan/index?key=${subkey}&referer=${referer}&endPoint=${endPoint}`,
    });
  },
})
</script>

添加公众号关注

微信提供了在扫二维码的场景下展示的公众号组件<official-account></official-account>, 所以在业务上主要兼容非扫码进入的场景(scene!==1011)。我们可以利用 web-view 组件跳转到关联的公众号上,公众号发布一篇关注的文章,就能解决。注意:需要在开发管理->开发设置->服务器域名 中添加 https://mp.weixin.qq.com