【xrframe】优化ar相机中加载模型效果

发布于:2024-05-09 ⋅ 阅读:(27) ⋅ 点赞:(0)

方法一:定义渲染width和height

//组件生命周期:在视图层布局完成后执行
 ready() {
    const info = wx.getSystemInfoSync();//在小程序中同步获取系统信息
    const width = info.windowWidth;//获取屏幕的宽度(单位为物理像素)
    const height = info.windowHeight;//获取屏幕的高度(单位为物理像素)
    const dpi = info.pixelRatio;//设备像素比,即物理像素与逻辑像素之间的比率
    this.setData({
      width,
      height,
      renderWidth: width * dpi * this.data.dpiScale,//与dpi,this.data.dpiScale相乘将逻辑像素转换为物理像素,同时考虑了 dpiScale影响因子
      renderHeight: height * dpi * this.data.dpiScale,
    });
  },

width(宽度): 用于设置 AR 相机的水平分辨率,即摄像头画面的宽度。较高的值会导致更高的水平分辨率,使画面更清晰,但也会增加性能负担。
height(高度): 用于设置 AR 相机的垂直分辨率,即摄像头画面的高度。与宽度类似,较高的值会导致更高的垂直分辨率,画面更清晰,但也会增加性能负担。

默认情况下,小程序 AR 相机的 width 和 height 的渲染宽度和高度与屏幕的宽度和高度相同,即等于设备的物理像素分辨率。

此外,自定义组件内置的属性包括:

id: 组件的唯一标识符
disable-scroll: 控制是否禁止滚动。
style: 用于设置组件的样式,可以包含各种 CSS 样式属性,如width、height、top、left等。
markerImg: 设置 AR 标记的图像。
bind:arTrackerState: 用于绑定 AR 跟踪器状态的事件处理函数。

<!-- 1. 使用xrframe自定义组件 渲染ar和模型 - -->
<xr-ar-2dmarker 
	disable-scroll 
	id="main-frame" 
	width="{{renderWidth}}"
	height="{{renderHeight}}" 
	style="width:{{width}}px;height:{{height}}px;top:{{top}}px;left:{{left}}px;display:block;" 
	markerImg="{{markerImg}}" 
	bind:arTrackerState="handleARTrackerState" />
<!-- 2. 使用threejs+VKSession在canvas 渲染ar和模型 -->
<canvas 
	type="webgl" 
	id="webgl" 
	style="width: {{width}}px; height: {{height}}px" 
	bindtouchstart="onTouchstart" 
	bindtouchend="onTouchEnd" 
	bindtouchmove="onTouchmove" />

方法二:后处理(PostProcess)使用快速抗锯齿 fxaa

<xr-camera clear-color="0.925 0.925 0.925 1" background="ar" is-ar-camera post-process="fxaa"/>

避坑:

  1. 官方最新xrframe限制提醒(主要是设备,开发基本库,xr-frame语法限制等)
  2. vision kit 版本限制
  3. 获取渲染上下文对象
    老版本wx.createCanvasContext(string canvasId, Object this)
    新版本wx.createSelectorQuery().select('#webgl').node().exec(res => { console.log('id为webgl的dom', res);
    注意:在自定义组件或包含自定义组件的页面中,应使用 this.createSelectorQuery() 来代替wx.createSelectorQuery()否则无法获取到上下文
  4. 兼容小程序的threejs库:threejs.miniprogramthree-platformize

原生init npm 生成package.json
uniapp 使用 npm init -y
npm i threejs-miniprogram
小程序工具栏,【工具】→ “构建npm”,即可完成npm构建

总结: xrframe组件渲染ar轻量好上手,threejs对模型操作和自定义手势更灵活

学习参考:
小程序官方xr-frame-demo