ShowView Viewer SDK

在網頁中載入並展示珍庫 3D 模型,控制背景、環境、鏡面、材質交互與渲染質量。

00 · START · 快速開始 | new ShowView(container, options, loadedCallback, errCallBack)

創建 Viewer 實例

ShowView 透過建構函式創建實例,內部會初始化渲染器、載入模型並接管相機控制。 頁面中需要預先準備一個 canvas 元素,把它的 id 傳給 container。

引數型別必填說明
containerstring是承載渲染畫面的 canvas 元素的 id。元素需在呼叫前已存在於 DOM 中。
optionsParameters是配置對象,欄位見下表。傳入空對象時不載入模型,僅初始化渲染環境。
loadedCallbackFunction是模型與場景載入完成後觸發。讀取初始狀態(自動旋轉、材質交互列表、背景等)應放在這裡。
errCallBackFunction是載入失敗時觸發,引數為錯誤對象。用於關閉 loading 或提示用戶。

options 配置項

即 Parameters 介面,所有欄位均為可選。

引數型別必填說明
modelUrlstring否模型文件地址(glb / gltf)。不傳則只初始化空場景,可後續用 changeSceneModel 載入。
backgroundUrlstring否背景圖地址。
enableAutoRotateboolean否是否開啟自動旋轉。模型自帶該配置時,載入後會以模型內的設置為準。
rotateDirection'left' | 'right'否自動旋轉方向,默認 right。
sceneScalenumber否場景初始縮放,對應相機 zoom,默認 1。
isSceneAnimationboolean否是否啟用場景動畫。開啟後自動旋轉會被關閉,且禁用鼠標左鍵拖拽。
pcViewerModelViewerScaleModel否PC 端渲染精度檔位,取值 0–4。數值越高越清晰,但渲染效能越差,建議設為 2。
mobileViewerModelViewerScaleModel否移動端渲染精度檔位,取值 0–4。數值越高越清晰,但渲染效能越差;移動端算力有限,建議設為 1.5。
autoUpdateboolean否是否每幀持續重繪,默認 false。默認按需重繪更省電,動態材質等場景才需開啟。
import { ShowView } from './JTShowView.mjs'

let editor: ShowView

// 頁面中需有 <canvas id="mcanvas"></canvas>
const init = async (data) => {
  const url = data.resourceUrl
  globalProperties?.showLoadding(true)

  editor = new ShowView(
    'mcanvas',
    {
      modelUrl: url,
      enableAutoRotate: true,
    },
    // 載入完成:讀取模型自帶的狀態並回填 UI
    async () => {
      // 自動旋轉
      const isAutoRotate = editor.getAutoRotate()
      changeEffectValue(isAutoRotate, 'startRotate')

      // 材質交互列表,決定是否顯示材質面板
      const interaction: MaterialInteractionData[] = await editor.getInterActionList()

      // 地面陰影
      const showGroundShadow = editor.getGroundShadow()
      changeEffectValue(showGroundShadow, 'showGroundShadow')

      // 原始背景:沒有背景圖時用背景色生成縮圖
      let background = await editor.getBackgroundImage()
      if (!background) {
        const color = `#${editor.getBackgroundColor()}`
        background = Utils.generateBase64ByColor(color)
      }

      // 原始環境球
      const environment = await editor.getEnvirmentImage()

      globalProperties?.showLoadding(false)
    },
    // 載入失敗
    () => {
      globalProperties?.showLoadding(false)
    },
  )
}
創建實例並在載入完成後讀取初始狀態。本頁程式碼示例均取自分享頁 Home.vue 的實際用法
實例是單例

建構函式會把實例掛到 ShowView.instance 上, 任何位置都能用 ShowView.getInstance() 取回, 不必自己層層傳遞。重複 new 會覆蓋前一個實例。

import { ShowView } from './JTShowView.mjs'

// 不必層層傳遞實例,任何位置都能取回
const editor: ShowView = ShowView.getInstance()
editor.setEnableAutoRotate(false)
在其他模組中取回已創建的實例

01 · MODEL · 模型 | 3 個方法

模型載入與銷燬

changeSceneModel(modelURL, loadedCallback, errCallBack) async

替換當前場景中的模型。內部會重置材質交互、重新計算包圍盒並讓相機重新適配模型。

引數型別必填說明
modelURLstring是新模型的文件地址。
loadedCallbackFunction是載入完成回撥。
errCallBackFunction是載入失敗回撥,引數為錯誤對象。
const changeModel = (url: string) => {
  editor.changeSceneModel(
    url,
    () => {
      globalProperties?.showLoadding(false)
    },
    () => {
      globalProperties?.showLoadding(false)
    },
  )
}

dispose()

銷燬 viewer,釋放渲染器與場景佔用的視訊記憶體。頁面解除安裝或跳轉到其他頁面前必須呼叫,否則會造成視訊記憶體洩漏。

// 跳轉到試戴頁等其他頁面前呼叫
editor.dispose()

ShowView.getInstance() static

獲取當前已創建的 ShowView 實例。

返回 ShowView 當前實例;尚未創建時為 undefined。

const editor: ShowView = ShowView.getInstance()

02 · ENV · 背景與環境 | 7 個方法

背景與環境貼圖

背景是可見的畫面底圖,環境貼圖決定金屬與寶石的反射。兩者都支持傳空並把 isResetOri 置為 true 來恢復模型自帶的原始設置。

setBackground(backgroundUrl, isResetOri) async

設置背景圖。傳入地址時載入該圖;isResetOri 為 true 時恢復模型的原始背景,此時 backgroundUrl 可傳空字串。

引數型別必填說明
backgroundUrlstring條件isResetOri 為 true 時可傳空(該引數不參與);否則為背景圖地址,傳空字串時使用默認漸變背景。
isResetOriboolean是是否恢復為模型自帶的原始背景。為 true 時忽略 backgroundUrl。
// 背景列表點選:有地址就載入,沒有地址(「默認」項)就恢復原始背景
const selectResource = (data: { resource: resourceItem }) => {
  const editor: ShowView = ShowView.getInstance()
  const { resourceUrl = '' } = data.resource

  resourceUrl
    ? editor.setBackground(resourceUrl, false)
    : editor.setBackground(resourceUrl, true)
}

changeEnvironment(environmentUrl, isResetOri) async

更換環境貼圖,影響模型表面的反射與整體光照氛圍。isResetOri 為 true 時恢復原始環境貼圖,此時 environmentUrl 可傳空字串。

引數型別必填說明
environmentUrlstring條件isResetOri 為 true 時可傳空(該引數不參與);否則為環境貼圖地址(hdr / jpg / png)。
isResetOriboolean是是否恢復為模型自帶的原始環境貼圖。
// 與背景同一套邏輯:空地址表示恢復模型自帶的環境球
resourceUrl
  ? editor.changeEnvironment(resourceUrl, false)
  : editor.changeEnvironment(resourceUrl, true)

getBackgroundImage() async

獲取當前背景的縮圖,可用於在 UI 中顯示「默認背景」選項。

返回 Promise<string> 背景圖地址;當前背景為純色時返回空值。

// 在 loadedCallback 中構造「默認背景」這一項的縮圖
let background = await editor.getBackgroundImage()

getBackgroundColor()

獲取當前背景色。

返回 string 十六進位制顏色值,不含 # 字首。

getEnvirmentImage() async

獲取當前環境貼圖的縮圖。

返回 Promise<string> 環境貼圖地址。

const environment = await editor.getEnvirmentImage()

setCanvasBackground(canvas)

把一個 canvas 作為背景。適合把攝像頭畫面或自繪內容作為背景,用於試戴等場景。

引數型別必填說明
canvasHTMLCanvasElement是作為背景內容的 canvas 元素。

setVideoTexture(canvas)

把 canvas 透過視頻流作為背景。相比 setCanvasBackground 走增量上傳,動態內容下效能更好;瀏覽器不支持時自動降級為 setCanvasBackground。

引數型別必填說明
canvasHTMLCanvasElement是作為背景內容的 canvas 元素。

返回 () => void | null 清理函式,呼叫後停止視頻流並釋放貼圖;降級時返回 null。

返回的清理函式需要在切換背景或解除安裝頁面時呼叫,否則攝像頭流不會釋放。

const cleanup = editor.setVideoTexture(cameraCanvas)

// 退出時釋放
cleanup?.()

03 · ROTATE · 自動旋轉 | 3 個方法

自動旋轉控制

setEnableAutoRotate(value)

開啟或關閉自動旋轉。用戶拖拽時會臨時暫停,鬆手後恢復。

引數型別必填說明
valueboolean是true 開啟,false 關閉。
editor.setEnableAutoRotate(true)

getAutoRotate()

讀取當前自動旋轉狀態。模型自帶該配置,建議在 loadedCallback 中呼叫以同步 UI 開關。

返回 boolean 當前是否處於自動旋轉狀態。

// 在 loadedCallback 中把模型自帶的狀態同步給面板開關
const isAutoRotate = editor.getAutoRotate()
changeEffectValue(isAutoRotate, 'startRotate')

setRotateDirection(rotateDirection = 'right')

設置自動旋轉方向。

引數型別必填說明
rotateDirection'left' | 'right'否旋轉方向,默認 right。
editor.setRotateDirection('left')

04 · GROUND · 鏡面與陰影 | 6 個方法

地面鏡面與陰影

鏡面是模型下方的反射面,陰影是模型投在地面上的接觸陰影,兩者獨立控制。

showMirror(flag)

顯示或隱藏地面鏡面反射。

引數型別必填說明
flagboolean是是否顯示鏡面。
// 特效面板的開關與滑塊統一走一個分發函式
const changeEffectValue = (
  value: boolean | number | 'left' | 'right',
  key: keyof effectPaneValue,
) => {
  switch (key) {
    case 'showMirror':
      editor.showMirror(value)
      break
    case 'mirrorOpacity':
      editor.changeMirrorOpacity(value)
      break
    case 'mirrorStrength':
      editor.changeMirrorStrength(value)
      break
    case 'showGroundShadow':
      editor.showGroundShadow(value)
      break
    case 'startRotate':
      editor.setEnableAutoRotate(value as boolean)
      break
    case 'rotateDirection':
      editor.setRotateDirection(value as 'left' | 'right')
      break
    case 'quality':
      editor.setViewerStanderScale(value as number)
      break
  }
  // 同步面板自身的狀態
  effectPaneValue.value[key] = value as never
}

changeMirrorOpacity(opacity)

調整鏡面透明度。

引數型別必填說明
opacitynumber是透明度,取值 0–1。
// 面板中鏡面透明度滑塊,默認值 1
editor.changeMirrorOpacity(0.6)

changeMirrorStrength(opacity)

調整鏡面反射強度。

引數型別必填說明
opacitynumber是反射強度,取值 0–1。
// 面板中鏡面反射強度滑塊,默認值 0.5
editor.changeMirrorStrength(0.5)

showGroundShadow(flag)

顯示或隱藏地面陰影。

引數型別必填說明
flagboolean是是否顯示陰影。
editor.showGroundShadow(true)

getGroundShadow()

讀取地面陰影的開啟狀態,用於在載入完成後同步 UI。

返回 boolean 當前是否顯示地面陰影。

const showGroundShadow = editor.getGroundShadow()
changeEffectValue(showGroundShadow, 'showGroundShadow')

isGroundEnabled()

判斷地面是否可用。

返回 boolean 地面外掛是否啟用。

05 · MATERIAL · 材質交互 | 5 個方法

材質交互

材質交互是在編輯器中預先配置的可切換材質組。每一組有唯一的 uuid 和一個材質陣列,前端據此渲染出「換色 / 換材質」面板。

相關型別

getInterActionList 返回 MaterialInteractionData[]。一個交互組繫結若干模型對象(objecUUids / objectInfos),並提供一組可選材質(materialData);activeActionMaterial 的兩個引數分別對應組的 uuid 與 materialData 的下標。

interface MaterialInteractionData {
  /** 交互組的唯一標識,作為 activeActionMaterial 的 actionUUid */
  uuid: string
  /** 交互組名稱,可直接用作面板的 tab 標題 */
  name: string
  /** 該組繫結的模型對象 uuid 列表 */
  objecUUids: string[]
  /** 該組繫結的模型對象信息 */
  objectInfos: InteractionObjectInfo[]
  /** 可切換的材質列表,下標即 activeActionMaterial 的 materialIndex */
  materialData: InteractionMaterialData[]
}

interface InteractionObjectInfo {
  name: string
  uuid: string
}

interface InteractionMaterialData {
  uuid: string
  /** 材質縮圖,用於面板中的色塊 */
  icon: string
  /** 材質名稱 */
  name: string
  data: any
}

getInterActionList() async

獲取模型的材質交互列表。應在 loadedCallback 中呼叫,用它來決定是否顯示材質切換面板。

返回 Promise<MaterialInteractionData[]> 交互組陣列,每項含 uuid、name、objecUUids、objectInfos、materialData。

// loadedCallback 中初始化材質面板
const interaction: MaterialInteractionData[] = await editor.getInterActionList()

activeActionMaterial(actionUUid, materialIndex) async

啟用指定交互組中的某個材質,即執行一次材質切換。

引數型別必填說明
actionUUidstring是交互組的 uuid,來自 getInterActionList 返回項的 uuid。
materialIndexnumber是該組 materialData 中的材質下標。
// 交互組 uuid,材質下標
          editor.activeActionMaterial(actionUUid, data.index as number)

resetInterActionMaterial()

把所有交互材質重置為初始狀態。

editor.resetInterActionMaterial()

getMaterialInterActionConfig()

導出當前的材質交互配置,含用戶已選中的材質。用於把當前搭配狀態傳遞到試戴頁等其他頁面。

返回 sceneMapData 含 resourceUrl、category_type、materialAction 的配置對象。

// 跳轉試戴頁:把當前搭配寫成記憶體文件,用 blob URL 傳遞
const toTryon = (path: TRYON_ICON_BUTTON_IDS) => {
  const productInfo = scene.getSceneResourceInfo
  const materialInteraction: sceneMapData = editor.getMaterialInterActionConfig()
  const { resourceUrl, category_type = 1, try_finger_config = '' } = productInfo

  materialInteraction.category_type = Number(category_type)
  materialInteraction.resourceUrl = resourceUrl
  materialInteraction.try_finger_config = try_finger_config

  const content = JSON.stringify(materialInteraction, undefined, 4)
  const blob = new Blob([content], { type: 'text/json' })
  const mapUrl = URL.createObjectURL(blob)

  // 離開當前頁前釋放視訊記憶體
  editor.dispose()

 
}

parseMaterialInterActionConfig(data) async

還原一份材質交互配置,與 getMaterialInterActionConfig 配對使用。

引數型別必填說明
datasceneMapData是getMaterialInterActionConfig 導出的配置對象。
const config = await fetch(mapUrl).then((r) => r.json())
await editor.parseMaterialInterActionConfig(config)

06 · QUALITY · 渲染質量 | 2 個方法

渲染精度檔位

檔位越高越清晰、越耗效能。移動端建議不超過 2;可結合 options 裡的 pcViewerModel 與 mobileViewerModel 設置初始檔位。

setViewerStanderScale(model)

設置渲染精度檔位。0 保持不變,1–4 分別對應渲染倍率 1、1.5、2、2.5。

引數型別必填說明
modelViewerScaleModel是檔位,取值 0 | 1 | 2 | 3 | 4。
 
      // 用戶切換檔位
      editor.setViewerStanderScale(2)

getViewerStanderScale()

讀取當前渲染精度檔位。

返回 number 當前檔位 0–4。

07 · CONTROL · 控制器速度 | 3 個方法

相機控制器速度

三個方法分別調節旋轉、平移與縮放的手感,數值越大越靈敏。

setControlRotationSpeed(speed)

設置拖拽旋轉速度,同時作用於水平與垂直方向。

引數型別必填說明
speednumber是旋轉速度。
editor.setControlRotationSpeed(1.2)

setControlTruckSpeed(speed)

設置平移速度,對應鼠標右鍵拖拽。

引數型別必填說明
speednumber是平移速度。

setControlScaleSpeed(speed)

設置滾輪縮放速度。

引數型別必填說明
speednumber是縮放速度。

08 · MISC · 其他 | 2 個方法

視窗縮 放獲取背景圖

onSizeChange()

按視窗尺寸重新計算相機比例、渲染尺寸與背景縮放。容器尺寸變化時呼叫。

window.addEventListener('resize', () => {
  ShowView.getInstance()?.onSizeChange()
})

getBackGroundImg()

把原始背景繪製到 canvas 並導出為 base64。

返回 string PNG 格式的 base64 資料。

08 · DEMO · 完整示例 | 載入模型 + 切換背景 + 材質交互 + 銷燬

一個可執行的最小頁面

<template>
  <canvas id="mcanvas"></canvas>
</template>

<script setup lang="ts">
 
import { ShowView } from './JTShowView.mjs'
 
let editor: ShowView
 
  editor = new ShowView(
    'mcanvas',
    {
      modelUrl: 'https://example.com/models/ring.glb',
      enableAutoRotate: true,
      rotateDirection: 'right',
      pcViewerModel: 2,
      mobileViewerModel: 1,
    },
    // 載入完成
    async () => {
      // 自動旋轉以模型自帶配置為準
      const isAutoRotate = editor.getAutoRotate()

      // 材質交互:無交互組時應隱藏材質入口
      const interaction = await editor.getInterActionList()
    
      // 地面效果
      const showGroundShadow = editor.getGroundShadow()
      editor.showMirror(true)
      editor.changeMirrorOpacity(1)
      editor.changeMirrorStrength(0.5)
    },
    // 載入失敗
    (err) => console.error('載入失敗', err),
  )
})
 
 
 
</script>
包含實例創建、狀態讀取、交互繫結與資源釋放
点任意处或 Esc 关闭