three.js

CSS3DRendering in Three.js

example code in tutorial site

Coding Drill

Hey guys! I'm learning Three.js with Three.js Cookbook in my daily coding to skill up. In this post, I pick one of trick in the book then I'm going to explain how to use it. That's CSS3DRendering. First of all, do you know what the CSS3DRendering is? As you know, CSS3D Transforms are natively supported by CSS transform property. So you can translate, rotate, scale DIV element with the CSS transforms such as translate3d. But if you'd like to animate DIV element in 3D wold in Three.js, CSS3DRendering is the solution. This library uses internally native CSS transforms. Though the CSS3DRendering is not an exact function in Three.js, you can import the plugin easily. If you don't know CSS transforms, visit here to learn first.

Create CSS3DObject

To use CSS3dRendering, you have to import the library first, which is provided from this repository.

import { CSS3DRenderer, CSS3DObject } from 'three/examples/jsm/renderers/CSS3DRenderer'

CSS3DRendering uses CSS3DObject instead of THREE.Mesh. To create CSS3DObject, you have to get DOM element with string type. I've just define directly it in JavaScript. Then add the created CSS3DObject into scene like following a couple of code.

let divString = '<div>' +
'<h1>This is an H1 Element.</h1>' +
'<span class="large">Hello Three.js cookbook</span>' +
'<textarea> And this is a textarea</textarea>' +
'</div>';

function createCSS3DObject(s) {
  // convert the string to dome elements
  var wrapper = document.createElement('div');
  wrapper.innerHTML = s;
  var div = wrapper.firstChild;

  // set some values on the div to style it, standard CSS
  div.style.width = '375px';
  div.style.height = '375px';
  div.style.opacity = 1;
  div.style['will-change'] = 'all'
  div.style.transition = 'top 0.2s linear'
  div.style.background = new THREE.Color(Math.random() * 0xffffff).getStyle();

  // create a CSS3Dobject and return it.
  var object = new CSS3DObject(div);
  return object;
}

const cssElement = createCSS3DObject(divString);
scene.add(cssElement); 

Conclusion

I've just introduce how to use CSS3DRendering. Using the library, you can animate as the top of image.

mitsuyacider/react-css3drender-demo
Test for CSS3DRenderer using React. Contribute to mitsuyacider/react-css3drender-demo development by creating an account on GitHub.