准备工作
1. 在 微信公众平台 注册并登录小程序。
3. 符合接入要求,并申请试用视立方 WEBAR License,详见 腾讯云视立方控制台。
接入配置
1. 使用组件前需在小程序工程的
app.json
中声明要使用的插件。{"plugins": {"webarPlugin": {"version": "1.0.1","provider": "wx04445cff065100ed"}}}
2. 在小程序目录安装 npm 包:tencentcloud-webar-wx。
npm install tencentcloud-webar-wx
3. 打开微信开发者工具,工具 > 执行构建 npm。
使用 webar-camera 组件接入美颜
设置美颜、滤镜、美妆、贴纸
1. 在 page 的
.json
文件中定义需要引入的webar-camera
组件。{"usingComponents": {"webar-camera": "tencentcloud-webar-wx/webar-camera"}}
2. 在 page 的
.wxml
文件中使用组件。<webar-cameralicenseKey="{{licenseKey}}"appId="{{appId}}"authFunc="{{authFunc}}"plugin3d="{{plugin3d}}"bind:created="onArCreated"style="width: 100vw; height: 100vh"/>
3. 在 page 的
.js
文件中使用 webarContext 设置美颜特效。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() {const {uint8ArrayData, width, height} = this.sdk.takePhoto(); // takePhoto 方法返回当前画面的 buffer 数据const photoCanvasNode = await this.getCanvasNode('photo-canvas');photoCanvasNode.width = parseInt(width);photoCanvasNode.height = parseInt(height);const ctx = photoCanvasNode.getContext('2d');// 用 sdk 返回的数据创建 ImageData 对象const imageData = photoCanvasNode.createImageData(uint8ArrayData, width, height);// 将 ImageData 对象绘制到 canvas 上ctx.putImageData(imageData,0,0,0,0,width,height);// 将 canvas 保存为本地图片wx.canvasToTempFilePath({canvas: photoCanvasNode,x: 0,y: 0,width: width,height: height,destWidth: width,destHeight: height,success: (res) => {// 保存照片到本地wx.saveImageToPhotosAlbum({filePath: res.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 | 是 | |
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 实例方法
鉴权方法 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 };