一、准备工作
1. 在 微信公众平台 注册并登录小程序。
2. 在 微信公众平台 添加小程序插件:视立方 WEBAR。
3. 符合接入要求,并申请试用视立方 WEBAR License,详见 腾讯云视立方控制台。
二、接入配置
1. 使用组件前需在小程序工程的app.json中声明要使用的插件。
{ "plugins": { "webarPlugin": { "version": "latest", "provider": "wx04445cff065100ed" } }}
2. 在小程序目录安装 npm 包:tencentcloud-webar-wx。
npm install tencentcloud-webar-wx
3. 打开微信开发者工具,工具 > 执行构建 npm。
三、设置美颜、滤镜、美妆、贴纸
webar-camera 组件使用微信组件 camera 进行封装,适用于拍摄录像场景下的美颜特效处理。
1. 在 page 的.json文件中定义需要引入的webar-camera组件。
{ "usingComponents": { "webar-camera": "tencentcloud-webar-wx/webar-camera" }}
2. 在 page 的.wxml文件中使用组件。
<webar-camera licenseKey="{{licenseKey}}" appId="{{appId}}" authFunc="{{authFunc}}" plugin3d="{{plugin3d}}" bind:created="onArCreated" style="width: 100vw; height: 100vh"/>
组件 webar-camera 的使用方法和微信原生标签 camera 的方法一致,可参考微信小程序标签 camera 的文档说明,美颜特效相关参数请参见 组件属性说明。
3. 在 page 的.js文件中使用 webarContext 设置美颜特效。
webar-camera 会通过 created 事件返回 WebarContext,详情请参见 API 文档。
onArCreated(event) { const webarContext = event.detail; this.sdk = webarContext; // 设置美颜 webarContext.setBeautify({ whiten: 0.5, dermabrasion: 0.6 }); // 设置滤镜 webarContext.setFilter(id, 1); // 设置美妆、特效、贴纸 webarContext.setEffect([{ id, intensity:1 }]);},
四、拍照与录像
拍照录像SDK 会返回包含宽高和 buffer 数据的对象,用户可以通过自己页面内的 2d canvas 绘制此数据并导出为图片文件。async takePhoto() { // 插件版本大于 1.0.14 可用 const {tempFilePath, uint8ArrayData, width, height} = this.sdk.takePhoto(); // takePhoto 方法返回当前画面的 buffer 数据 wx.saveImageToPhotosAlbum({ filePath: tempFilePath });}注意当小程序切换后台或检测到手机锁屏时,需要调用 stopRecord 停止录像,否则可能出错。// 开始录像startRecord() { this.sdk.startRecord()}// 结束录像async stopRecord() { const res = await this.sdk.stopRecord(); // 保存录像到本地 wx.saveVideoToPhotosAlbum({ filePath: res.tempFilePath })}
五、组件美颜特效属性说明
| 属性 | 类型 | 默认值 | 必填 | 说明 |
| licenseKey | string | "" | 是 | 腾讯云视立方 licenseKey |
| appId | string | "" | 是 | 腾讯云 appid |
| authFunc | async function | null | 是 | 需返回 signature, timestamp,详见 WEBAR 鉴权方法,传递时请不要包含在对象中 |
| plugin3d | function | null | 否 | 3d 特效插件,开启 3d 贴纸时需传入 |
| beautify | Object | null | 否 | 初始美颜参数,取值范围:0 – 1,可用: whiten、dermabrasion、lift、shave、eye、chin |
| background | string | '' | 否 | 虚拟背景图片 url,域名需加入小程序白名单 |
| bindcreated | event | null | 否 | 美颜特效 SDK 初始化完成事件 |
| bindready | event | null | 否 | 美颜特效 SDK 加载完成事件 |
| binderror | event | null | 否 | 美颜特效 SDK 错误事件 |
六、webarContext 实例方法
获取可用滤镜列表、美妆列表、贴纸列表及设置美颜、滤镜、美妆、贴纸等方法,详见 API 文档。
七、鉴权方法 authFunc 生成方式
const config = { appid: '你的腾讯云APPID', token: '你的Token',}const authFunc = async function() { const timestamp = Math.round(new Date().getTime() / 1000); const signature = sha256(timestamp + config.token + config.appid + timestamp).toUpperCase(); return { signature, timestamp };
此方法仅测试时使用,为防止 token 泄露,发布时请使用服务端加密,详见 腾讯云-美颜特效 SDK 页面文档。
八、示例代码
详情请参见:示例项目。