ShowView Viewer SDK

Load and display a GemCool 3D model in a web page, and control the background, environment, mirror reflection, material interaction and render quality.

00 · START · Quick start | new ShowView(container, options, loadedCallback, errCallBack)

Creating a Viewer instance

ShowView is created through its constructor, which initialises the renderer, loads the model and takes over camera control. Prepare a canvas element on the page in advance and pass its id to container.

ParameterTypeRequiredDescription
containerstringYesThe id of the canvas element that renders the scene. The element has to exist in the DOM before the call.
optionsParametersYesConfiguration object; see the table below. Passing an empty object loads no model and only sets up the render environment.
loadedCallbackFunctionYesFires once the model and scene have loaded. Read the initial state here (auto rotation, material interaction list, background and so on).
errCallBackFunctionYesFires when loading fails; the argument is the error object. Use it to hide the loading indicator or tell the user.

options fields

This is the Parameters interface; every field is optional.

ParameterTypeRequiredDescription
modelUrlstringNoModel file URL (glb / gltf). Leave it out to initialise an empty scene only, and load a model later with changeSceneModel.
backgroundUrlstringNoBackground image URL.
enableAutoRotatebooleanNoWhether to start auto rotation. When the model carries this setting, the model's own value wins after loading.
rotateDirection'left' | 'right'NoAuto-rotation direction; right by default.
sceneScalenumberNoInitial scene scale, which maps to the camera zoom; 1 by default.
isSceneAnimationbooleanNoWhether to enable the scene animation. Turning it on disables auto rotation and left-button dragging.
pcViewerModelViewerScaleModelNoRender precision level on desktop, 0–4. Higher is sharper but slower; 2 is recommended.
mobileViewerModelViewerScaleModelNoRender precision level on mobile, 0–4. Higher is sharper but slower; mobile GPUs are limited, so 1.5 is recommended.
autoUpdatebooleanNoWhether to redraw every frame; false by default. Redrawing on demand saves power, so only turn this on for dynamic materials and similar cases.
import { ShowView } from './JTShowView.mjs'

let editor: ShowView

// the page needs <canvas id="mcanvas"></canvas>
const init = async (data) => {
  const url = data.resourceUrl
  globalProperties?.showLoadding(true)

  editor = new ShowView(
    'mcanvas',
    {
      modelUrl: url,
      enableAutoRotate: true,
    },
    // loaded: read the model's own state and back-fill the UI
    async () => {
      // auto rotation
      const isAutoRotate = editor.getAutoRotate()
      changeEffectValue(isAutoRotate, 'startRotate')

      // material interaction list, which decides whether the material panel shows
      const interaction: MaterialInteractionData[] = await editor.getInterActionList()

      // ground shadow
      const showGroundShadow = editor.getGroundShadow()
      changeEffectValue(showGroundShadow, 'showGroundShadow')

      // original background: build a thumbnail from the colour when there is no image
      let background = await editor.getBackgroundImage()
      if (!background) {
        const color = `#${editor.getBackgroundColor()}`
        background = Utils.generateBase64ByColor(color)
      }

      // original environment map
      const environment = await editor.getEnvirmentImage()

      globalProperties?.showLoadding(false)
    },
    // load failed
    () => {
      globalProperties?.showLoadding(false)
    },
  )
}
Creating the instance and reading the initial state once loading finishes. The code samples on this page come from the real usage in the share page's Home.vue
The instance is a singleton

The constructor attaches the instance to ShowView.instance , and you can retrieve it from anywhere with ShowView.getInstance() ; there is no need to thread it through layers, and calling new again overwrites the previous instance.

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

// no need to thread the instance through layers; retrieve it from anywhere
const editor: ShowView = ShowView.getInstance()
editor.setEnableAutoRotate(false)
Retrieving the created instance from another module

01 · MODEL · Model | 3 methods

Loading and destroying models

changeSceneModel(modelURL, loadedCallback, errCallBack) async

Replaces the model in the current scene. Internally it resets material interaction, recomputes the bounding box and re-fits the camera to the model.

ParameterTypeRequiredDescription
modelURLstringYesURL of the new model file.
loadedCallbackFunctionYesCallback for a successful load.
errCallBackFunctionYesCallback for a failed load; the argument is the error object.
const changeModel = (url: string) => {
  editor.changeSceneModel(
    url,
    () => {
      globalProperties?.showLoadding(false)
    },
    () => {
      globalProperties?.showLoadding(false)
    },
  )
}

dispose()

Destroys the viewer and releases the GPU memory used by the renderer and the scene. You must call it before the page unloads or navigates away, otherwise you leak GPU memory.

// call before navigating to another page such as try-on
editor.dispose()

ShowView.getInstance() static

Returns the ShowView instance that has been created.

Returns ShowView the current instance; undefined when none has been created yet.

const editor: ShowView = ShowView.getInstance()

02 · ENV · Background and environment | 7 methods

Background and environment maps

The background is the visible backdrop of the image, and the environment map drives the reflections on metal and gemstones. Both accept an empty value plus isResetOri set to true to restore the model's own original settings.

setBackground(backgroundUrl, isResetOri) async

Sets the background image. Pass a URL to load that image; when isResetOri is true the model's original background is restored, and backgroundUrl can be an empty string.

ParameterTypeRequiredDescription
backgroundUrlstringConditionalCan be empty when isResetOri is true (the argument is then unused); otherwise it is the background image URL, and an empty string falls back to the default gradient background.
isResetOribooleanYesWhether to restore the model's own original background. When true, backgroundUrl is ignored.
// background list click: load when there is a URL, otherwise (the "Default" item) restore the original background
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

Swaps the environment map, which affects surface reflections and the overall lighting mood. When isResetOri is true the original environment map is restored, and environmentUrl can be an empty string.

ParameterTypeRequiredDescription
environmentUrlstringConditionalCan be empty when isResetOri is true (the argument is then unused); otherwise it is the environment map URL (hdr / jpg / png).
isResetOribooleanYesWhether to restore the model's own original environment map.
// same logic as the background: an empty URL restores the model's own environment map
resourceUrl
  ? editor.changeEnvironment(resourceUrl, false)
  : editor.changeEnvironment(resourceUrl, true)

getBackgroundImage() async

Returns a thumbnail of the current background, which you can use for a "Default background" option in your UI.

Returns Promise<string> the background image URL; returns an empty value when the current background is a solid colour.

// build the thumbnail for the "Default background" item inside loadedCallback
let background = await editor.getBackgroundImage()

getBackgroundColor()

Returns the current background colour.

Returns string a hex colour value without the # prefix.

getEnvirmentImage() async

Returns a thumbnail of the current environment map.

Returns Promise<string> the environment map URL.

const environment = await editor.getEnvirmentImage()

setCanvasBackground(canvas)

Uses a canvas as the background. Good for putting a camera feed or your own drawing behind the model, as in virtual try-on.

ParameterTypeRequiredDescription
canvasHTMLCanvasElementYesThe canvas element used as the background content.

setVideoTexture(canvas)

Uses a canvas as the background through a video stream. Compared with the incremental upload of setCanvasBackground this performs better with dynamic content, and it falls back to setCanvasBackground automatically when the browser does not support it.

ParameterTypeRequiredDescription
canvasHTMLCanvasElementYesThe canvas element used as the background content.

Returns () => void | null a cleanup function that stops the video stream and releases the texture once called; returns null when it fell back.

Call the returned cleanup function when you switch the background or unload the page, otherwise the camera stream is never released.

const cleanup = editor.setVideoTexture(cameraCanvas)

// release on exit
cleanup?.()

03 · ROTATE · Auto rotation | 3 methods

Auto-rotation control

setEnableAutoRotate(value)

Turns auto rotation on or off. Dragging pauses it temporarily and releasing the mouse resumes it.

ParameterTypeRequiredDescription
valuebooleanYestrue turns it on, false turns it off.
editor.setEnableAutoRotate(true)

getAutoRotate()

Reads the current auto-rotation state. The model carries this setting, so call it in loadedCallback to keep your UI switch in sync.

Returns boolean whether auto rotation is currently on.

// sync the model's own state to the panel switches inside loadedCallback
const isAutoRotate = editor.getAutoRotate()
changeEffectValue(isAutoRotate, 'startRotate')

setRotateDirection(rotateDirection = 'right')

Sets the auto-rotation direction.

ParameterTypeRequiredDescription
rotateDirection'left' | 'right'NoRotation direction; right by default.
editor.setRotateDirection('left')

04 · GROUND · Mirror and shadow | 6 methods

Ground mirror and shadow

The mirror is the reflective plane below the model, and the shadow is the contact shadow the model casts on the ground. They are controlled independently.

showMirror(flag)

Shows or hides the ground mirror reflection.

ParameterTypeRequiredDescription
flagbooleanYesWhether to show the mirror.
// one dispatcher handles both the toggles and the sliders of the effects panel
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
  }
  // keep the panel's own state in sync
  effectPaneValue.value[key] = value as never
}

changeMirrorOpacity(opacity)

Adjusts mirror opacity.

ParameterTypeRequiredDescription
opacitynumberYesOpacity, 0–1.
// mirror opacity slider in the panel, default 1
editor.changeMirrorOpacity(0.6)

changeMirrorStrength(opacity)

Adjusts mirror reflection strength.

ParameterTypeRequiredDescription
opacitynumberYesReflection strength, 0–1.
// mirror reflection strength slider in the panel, default 0.5
editor.changeMirrorStrength(0.5)

showGroundShadow(flag)

Shows or hides the ground shadow.

ParameterTypeRequiredDescription
flagbooleanYesWhether to show the shadow.
editor.showGroundShadow(true)

getGroundShadow()

Reads whether the ground shadow is on, for syncing your UI once loading finishes.

Returns boolean whether the ground shadow is currently shown.

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

isGroundEnabled()

Checks whether the ground is available.

Returns boolean whether the ground plugin is enabled.

05 · MATERIAL · Material interaction | 5 methods

Material interaction

Material interaction is a set of switchable material groups configured in the editor beforehand. Each group has a unique uuid and an array of materials, which the front end uses to render a colour / material picker panel.

Related types

getInterActionList returns MaterialInteractionData[]. One interaction group binds several model objects (objecUUids / objectInfos) and offers a set of selectable materials (materialData); the two arguments of activeActionMaterial are the group uuid and the index into materialData.

interface MaterialInteractionData {
  /** unique id of the interaction group, used as the actionUUid of activeActionMaterial */
  uuid: string
  /** group name; use it directly as the panel tab title */
  name: string
  /** uuids of the model objects bound to this group */
  objecUUids: string[]
  /** info of the model objects bound to this group */
  objectInfos: InteractionObjectInfo[]
  /** switchable materials; the index is the materialIndex of activeActionMaterial */
  materialData: InteractionMaterialData[]
}

interface InteractionObjectInfo {
  name: string
  uuid: string
}

interface InteractionMaterialData {
  uuid: string
  /** material thumbnail, used for the swatch in the panel */
  icon: string
  /** material name */
  name: string
  data: any
}

getInterActionList() async

Returns the model's material interaction list. Call it in loadedCallback and use it to decide whether to show the material picker panel.

Returns Promise<MaterialInteractionData[]> an array of interaction groups, each with uuid, name, objecUUids, objectInfos and materialData.

// initialise the material panel inside loadedCallback
const interaction: MaterialInteractionData[] = await editor.getInterActionList()

activeActionMaterial(actionUUid, materialIndex) async

Activates one material in the given interaction group, which performs one material switch.

ParameterTypeRequiredDescription
actionUUidstringYesuuid of the interaction group, taken from the uuid of an item returned by getInterActionList.
materialIndexnumberYesIndex of the material within that group's materialData.
// interaction group uuid, material index
          editor.activeActionMaterial(actionUUid, data.index as number)

resetInterActionMaterial()

Resets all interaction materials to their initial state.

editor.resetInterActionMaterial()

getMaterialInterActionConfig()

Exports the current material interaction configuration, including the materials the user has already selected. Use it to carry the current combination over to another page such as try-on.

Returns sceneMapData a configuration object containing resourceUrl, category_type and materialAction.

// to the try-on page: write the current combination as an in-memory file and pass it as a 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)

  // release GPU memory before leaving the page
  editor.dispose()

 
}

parseMaterialInterActionConfig(data) async

Restores a material interaction configuration; use it together with getMaterialInterActionConfig.

ParameterTypeRequiredDescription
datasceneMapDataYesA configuration object exported by getMaterialInterActionConfig.
const config = await fetch(mapUrl).then((r) => r.json())
await editor.parseMaterialInterActionConfig(config)

06 · QUALITY · Render quality | 2 methods

Render precision level

The higher the level, the sharper and the more expensive. Keep it at 2 or below on mobile; set the starting level with pcViewerModel and mobileViewerModel in options.

setViewerStanderScale(model)

Sets the render precision level. 0 leaves it unchanged; 1–4 map to render ratios of 1, 1.5, 2 and 2.5.

ParameterTypeRequiredDescription
modelViewerScaleModelYesThe level, one of 0 | 1 | 2 | 3 | 4.
 
      // the user switches the level
      editor.setViewerStanderScale(2)

getViewerStanderScale()

Reads the current render precision level.

Returns number the current level, 0–4.

07 · CONTROL · Controller speed | 3 methods

Camera controller speed

The three methods tune the feel of rotation, panning and zoom; the higher the value, the more responsive.

setControlRotationSpeed(speed)

Sets the drag rotation speed, applied to both horizontal and vertical movement.

ParameterTypeRequiredDescription
speednumberYesRotation speed.
editor.setControlRotationSpeed(1.2)

setControlTruckSpeed(speed)

Sets the pan speed, used for right-button drag.

ParameterTypeRequiredDescription
speednumberYesPan speed.

setControlScaleSpeed(speed)

Sets the wheel zoom speed.

ParameterTypeRequiredDescription
speednumberYesZoom speed.

08 · MISC · Misc | 2 methods

Window resize and background export

onSizeChange()

Recomputes the camera aspect, render size and background scale from the window size. Call it when the container size changes.

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

getBackGroundImg()

Draws the original background onto a canvas and exports it as base64.

Returns string base64 data in PNG format.

08 · DEMO · Full example | Load a model + switch background + material interaction + destroy

A minimal runnable page

<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,
    },
    // loaded
    async () => {
      // auto rotation follows the model's own configuration
      const isAutoRotate = editor.getAutoRotate()

      // material interaction: hide the material entry when there are no interaction groups
      const interaction = await editor.getInterActionList()
    
      // ground effects
      const showGroundShadow = editor.getGroundShadow()
      editor.showMirror(true)
      editor.changeMirrorOpacity(1)
      editor.changeMirrorStrength(0.5)
    },
    // load failed
    (err) => console.error('load failed', err),
  )
})
 
 
 
</script>
Instance creation, state reading, interaction binding and resource release
点任意处或 Esc 关闭