DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > Livecoding Recap: Towards Declarative 3D Scenes With React and Three.js [Video]

Livecoding Recap: Towards Declarative 3D Scenes With React and Three.js [Video]

In this livecoding session, we show you how to create 2 3D, spinning cubes, using two popular JavaScript frameworks. Exciting right?!

Swizec Teller user avatar by
Swizec Teller
·
Jun. 27, 17 · Web Dev Zone · Tutorial
Like (1)
Save
Tweet
4.74K Views

Join the DZone community and get the full member experience.

Join For Free

17 years ago, in 6th grade, I set out to build a 3D spinning cube and failed miserably. You can’t do 3D without sine and cosine.

Today, I made it happen! Two 3D spinning cubes.

Image title


As promised, this week’s livecoding session happened on Monday. Together, we admired the speed of my new laptop, wondered why YouTube still garbles my voice and built two green spinning 3D cubes. Declaratively.


The main render code looks like this:

    <div className="App-intro">
                    <ThreeScene width={800} height={600}
                                style={{margin: '0 auto' }}>
                        <PerspectiveCamera fov={75}
                                           aspect={800/600}
                                           near={0.1}
                                           far={1000}
                                           position={{x: 0, y: 0, z: 30}}>

                            <Cube rotation={rotation1}
                                  position={{x: 2, y: 0, z: 25}}  />
                            <Cube rotation={rotation2}
                                  position={{x: -10, y: 5, z: 10 }} />

                        </PerspectiveCamera>
                    </ThreeScene>
                </div>

A ThreeScene, which is a scene done with Three.js, contains a PerspectiveCamera, which contains 2 Cube elements. Cube positions come from state, get changed on requestAnimationFramein an infinite loop, and voilà: two spinning cubes.

The goal was to come up with a declarative approach to creating 3D scenes. Write React components, use all the normal React idioms, and have stuff come out in 3D.

I’m sure someone’s already built a React-to-Three library, but I wanted to give it a shot myself. You can think of this as a proof of concept.

This is also the first time I’ve played with Three.js, and I have to say, it’s easier than I thought it would be. At least to render two cubes. Other stuff I’m sure is super hard.

Here’s how it works.

PS: Full code is on GitHub.

Step 1: A <ThreeScene>

class ThreeScene extends Component {
    scene = new THREE.Scene();
    renderer = new THREE.WebGLRenderer();

    componentDidMount() {
        this.updateThree(this.props);

        this.refs.anchor.appendChild(this.renderer.domElement);
    }
    componentDidUpdate() {
        this.updateThree(this.props);
    }

    updateThree(props) {
        const { width, height } = props;

        this.renderer.setSize(width, height);
    }

    getChildContext() {
        return {
            scene: this.scene,
            renderer: this.renderer
        }
    }

    render() {
        const { width, height, style } = this.props;

        return (
            <div ref="anchor" style={[{width, height}, style]}>
                 {this.props.children}
            </div>
        )
    }
}

ThreeScene.childContextTypes = {
    scene: PropTypes.object,
    renderer: PropTypes.object
}

A ThreeScene component defines a new Three.js Scene and a WebGLRenderer. Both are added into React Context via getChildContext.

Context is messy but it gives every child access to the scene and renderer. They’ll need the scene for rendering themselves, and the camera component will need access to the renderer.

In componentDidMount, we manually update the DOM and appendChild to the rendered anchor element. This mounts our Three.js canvas to the DOM.

Step 2: A <PerspectiveCamera>

Three.js comes with a bunch of different camera configurations, and I don’t know what they all mean. I think one of them, the StereoCamera, is meant for VR.

The base example uses PerspectiveCamera, so that’s what I used, too. This component sets up our camera and renders our scene.

class PerspectiveCamera extends Component {
    constructor(props) {
        super(props);

        this.updateThree(props);
    }
    componentDidUpdate() {
        this.updateThree(this.props);
        this._render();
    }

    updateThree(props) {
        const { fov, aspect, near, far, position } = this.props;

        this.camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
        this.camera.position.x = position.x;
        this.camera.position.y = position.y;
        this.camera.position.z = position.z;
    }

    componentDidMount() {
        this._render();
    }

    _render() {
        this.context.renderer.render(this.context.scene, this.camera);
    }

    render() {
        return <div>{this.props.children}</div>;
    }
}

PerspectiveCamera.contextTypes = {
    scene: PropTypes.object,
    renderer: PropTypes.object
}

We call updateThree when <PerspectiveCamera> is first initialized and whenever props or children update. This creates a new camera instance with updated properties.

I’m sure Three.js supports changing the field of view, aspect ratio, and other properties of an already instantiated camera, but there was no clear way of doing so. It looks like creating a new camera on every requestAnimationFrame doesn’t cause issues.

Every time React updates our component, we call _render. It performs the actual Three.js rendering of our scene.

Step 3: Two <Cube>s

Finally, our <Cube> components know how to render a 3D cube from props, and add themselves to the scene when mounted. They should remove themselves when unmounted, but I didn’t implement that part due to “Eh, it’s just an example.”

class Cube extends Component {
    componentWillMount() {
        this.geometry = new THREE.BoxGeometry(1, 1, 1);
        this.material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
        this.cube = new THREE.Mesh(this.geometry, this.material);

        this.context.scene.add(this.cube);
    }

    componentDidUpdate() {
        const { rotation, position } = this.props;

        this.cube.rotation.x = rotation.x;
        this.cube.rotation.y = rotation.y;

        this.cube.position.x = position.x;
        this.cube.position.y = position.y;
        this.cube.position.z = position.z;
    }

    render() {
        return null;
    }
}

Cube.contextTypes = {
    scene: PropTypes.object
}

Officially, a <Cube> component renders null. Unofficially, it adds itself to the scene with scene.add in componentWillMount.

When it’s being mounted, it also sets up the object itself with Geometry, adds a green Mesh, and updates its own rotation and position on every componentDidUpdate. This creates smooth animation if we change props often enough.

Every requestAnimationFrame is best.

Fin

And that’s how we can render Declarative 3D scenes in React. This has been a 2-hour experiment. With some more work, it could become a proper way to use Three.js with a React approach.

Surely someone’s already built that…

React (JavaScript library)

Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Java: Why Core-to-Core Latency Matters
  • How to Configure Git in Eclipse IDE
  • A Guide to Understanding Vue Lifecycle Hooks
  • How to Use Geofences for Precise Audience Messaging

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo