Three.js on node.js

Hello again,

can someone support me with a working example to run three.js on node.js and render objects and save the scene as an image?

I’ve been looking for a long time now and I am tired.

MANY!! thx in advance.

You can start with a threejs boilerplate that uses node

Here is one.

git clone https://github.com/Sean-Bradley/Three.js-Boilerplate-TS-Vite.git
cd Three.js-Boilerplate-TS-Vite
npm install

Start it
npm run dev

Visit http://localhost:5173/ in your browser.

Now change files in the project

./src/main.ts

change

- const renderer = new THREE.WebGLRenderer()
+ const renderer = new THREE.WebGLRenderer({ preserveDrawingBuffer: true });

and add to the end of the ./src/main.ts script

const screenshotButton = document.getElementById('screenshotButton') as HTMLButtonElement
screenshotButton.addEventListener('click', () => {
  const link = document.createElement('a')
  link.download = 'screenshot.png'
  link.href = renderer.domElement.toDataURL('image/png')
  link.click()
})

./src/style.css

add

#screenshotButton {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 10px 15px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  z-index: 1;
}
#screenshotButton:hover {
  background-color: #0056b3;
}

./index.html

add to body tag

  <body>
+   <button id="screenshotButton">Take Screenshot</button>
    <script type="module" src="/src/main.ts"></script>
  </body>

After saving changes, your browser should already be running the latest code.


Here is the same example but using importmaps and all in one file