DEV Community

Cover image for Three JS Examples : 1. Three JS Cube Animation
Jon Snow
Jon Snow

Posted on

Three JS Examples : 1. Three JS Cube Animation

Three.js is a cross-browser JavaScript library and application programming interface used to create and display animated 3D computer graphics in a web browser using WebGL.

Three js docs

Three JS Cube Animation

Source code

How to use Three JS in React JS

React-three-fiber is a React renderer for three.js

Installing react-three-fiber

npm install three @react-three/fiber 
Enter fullscreen mode Exit fullscreen mode

Create your first geometry

import { createRoot } from 'react-dom/client'
import React, { useRef, useState } from 'react'
import { Canvas, useFrame } from '@react-three/fiber'

function Box(props) {
  // This reference gives us direct access to the THREE.Mesh object
  const ref = useRef()
  // Hold state for hovered and clicked events
  const [hovered, hover] = useState(false)
  const [clicked, click] = useState(false)
  // Subscribe this component to the render-loop, rotate the mesh every frame
  useFrame((state, delta) => (ref.current.rotation.x += delta))
  // Return the view, these are regular Threejs elements expressed in JSX
  return (
      scale={clicked ? 1.5 : 1}
      onClick={(event) => click(!clicked)}
      onPointerOver={(event) => hover(true)}
      onPointerOut={(event) => hover(false)}>
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color={hovered ? 'hotpink' : 'orange'} />

    <ambientLight />
    <pointLight position={[10, 10, 10]} />
    <Box position={[-1.2, 0, 0]} />
    <Box position={[1.2, 0, 0]} />

Enter fullscreen mode Exit fullscreen mode


Live Demo

For more information

  1. Check my GitHub profile

  2. Subscribe my Youtube Channel

  3. Check out my Fiver profile if you need any freelancing work

  4. Follow me on Instagram

  5. Check out my Facebook Page
    Programming memes by Coder

  6. Linktree

Top comments (0)