Skip to main content
Documentation

Changing the Viewpoint

Read and update Five SDK viewpoint state in React.

In this chapter you will learn

  • What State is.
  • How to change the viewing direction/position in React via five.setState.
  • How to listen for stateChange and keep the UI in sync.

React example: switching modes

import { useEffect, useRef, useState } from 'react'
import { Five, Mode, parseWork } from '@realsee/five'

const workURL = 'https://vr-public.realsee-cdn.cn/release/static/image/release/five/work-sample/07bdc58f413bc5494f05c7cbb5cbdce4/work.json'

export default function FiveState() {
  const containerRef = useRef(null)
  const fiveRef = useRef(null)
  const [mode, setMode] = useState('Panorama')

  useEffect(() => {
    const five = new Five()
    fiveRef.current = five
    if (containerRef.current) five.appendTo(containerRef.current)
    fetch(workURL).then(r=>r.json()).then(json=>five.load(parseWork(json)))

    const onResize = () => five.refresh()
    const onState = (s) => setMode(s.mode)
    window.addEventListener('resize', onResize, false)
    five.on('stateChange', onState)

    return () => {
      window.removeEventListener('resize', onResize, false)
      five.off('stateChange', onState)
      five.dispose()
    }
  }, [])

  const switchMode = (m) => fiveRef.current?.setState({ mode: m })

  return (
    <div style={{ width: '100vw', height: '100vh' }}>
      <div ref={containerRef} style={{ width: '100%', height: '100%', overflow: 'hidden' }} />
      <div style={{ position: 'fixed', bottom: 16, left: 0, right: 0, display: 'flex', justifyContent: 'center', gap: 8 }}>
        <button className={mode==='Panorama'?'btn btn-primary':'btn btn-outline-primary'} onClick={()=>switchMode('Panorama')}>Panorama Walkthrough</button>
        <button className={mode==='Floorplan'?'btn btn-primary':'btn btn-outline-primary'} onClick={()=>switchMode('Floorplan')}>Space Overview</button>
      </div>
    </div>
  )
}

Key points in React:

  • Use useEffect to subscribe to stateChange, and call off and dispose in the cleanup function;
  • Mirror the current mode in local UI state so you can highlight the active button;
  • Change the viewpoint or mode via setState.