react three fiber lock object position in canvas

I’m new to Threejs and react-three-fiber. How to lock an object in canvas ( lock position, rotation ) when the perspective camera rotates and move. I want to make an object that avoids perspective camera movements and remain in a fixed position

current preview

enter image description here


You can use refs to access underlying objects, and thus modify their position, rotation, etc.

As PerspectiveCamera is an Object3D, you can add this mesh as a child so that they move together.

import { useRef } from 'react';
import { useThree } from '@react-three/fiber';

const MyMesh = () => {
  const { camera } = useThree();
  const ref = useRef();

  useEffect(() => {
    // Add mesh to camera
    const meshRef = ref.current;

    // Cleanup on unmount
    return () => {
  }, [camera, ref.current]);

  return <mesh ref={ref} position={[0, 0, -5]} />;

Here, I’m accessing Fiber’s camera through its context via the useThree hook.

Alternatively, you can copy the camera’s properties every frame and apply an offset. This will result in the same display behavior.

You can access the renderloop via the useFrame hook. This runs inside three, so there’s no overhead within React. It’s notable that you can access Fiber’s context from within the hook’s callback as well.

import { useRef } from 'react';
import { useFrame } from '@react-three/fiber';

const MyMesh = () => {
  const ref = useRef();

  useFrame(({ camera }) => {
    // Move mesh to be flush with camera

    // Apply offset

  return <mesh ref={ref} />;