VueJS

Awesome 3D experience with VueJS and TresJS: a beginner's guide

Mattia Magi
5 min read
Mattia - Awesome 3D experience with VueJS and TresJS: a beginner's guide
This article was written over 18 months ago and may contain information that is out of date. Some content may still be relevant, but please refer to official documentation for the latest information.

Awesome 3D experience with VueJS and TresJS: a beginner's guide

Vue.js developers are renowned for raving about the ease, flexibility, and speed of development their framework offers. Tres.js builds on this love for Vue by becoming the missing piece for seamless 3D integration. As a Vue layer for Three.js, Tres.js allows you to leverage the power of Three.js, a popular 3D library, within the familiar and beloved world of Vue components. This means you can create stunning 3D graphics and animations directly within your Vue applications, all while maintaining the clean and efficient workflow you've come to expect.

TresJS is a library specifically designed to make incorporating WebGL (the web's 3D graphics API) into your Vue.js projects a breeze. It boasts several key features that make 3D development with Vue a joy:

  • Declarative Approach: Build your 3D scenes like you would any other Vue component, leveraging the power and familiarity of Vue's syntax. This makes it intuitive and easy to reason about your 3D elements.
  • Powered by Vite: Experience blazing-fast development cycles with Vite's Hot Module Replacement (HMR) that keeps your scenes updated in real-time, even as your code changes.
  • Up-to-date Features: Tres.js stays on top of the latest Three.js releases, ensuring you have immediate access to the newest features and functionality.
  • Thriving Ecosystem: The Tres.js ecosystem offers many resources to enhance your development experience. This includes:
    • Cientos: A collection of pre-built components and helpers that extend the capabilities of Tres.js, allowing you to focus on building your scene's functionality rather than reinventing the wheel (https://cientos.tresjs.org/).
    • TresLeches: A powerful state management solution specifically designed for 3D applications built with Tres.js (https://tresleches.tresjs.org/).

You can try TresJS online using their official Playground or on their StackBlitz starter.

But now, let's dive into a quick code example to showcase the simplicity of creating a 3D scene with TresJS.

Setup

First, install the package:

npm install @tresjs/core three

And then, if you are using Typescript, be sure to install the types:

npm install @types/three -D

If you are using Vite, now you need to modify your vite.config.ts file in this way to make the template compiler work with the custom renderer:

import { templateCompilerOptions } from '@tresjs/core'

export default defineConfig({
  plugins: [
    vue({
      // Other config
      ...templateCompilerOptions
    }),
  ],
})

Create our Scene

Imagine a 3D scene as a virtual stage. To bring this stage to life, we need a few key players working together:

  1. Scene: Think of this as the container that holds everything in your 3D world. It acts as the canvas where all the objects, lights, and the camera reside, defining the overall environment.

  2. Renderer: This is the magician behind the curtain, responsible for taking all the elements in your scene and translating them into what you see on the screen. It performs the complex calculations needed to transform your 3D scene into 2D pixels displayed on your browser.

  3. Camera: Like a real camera, this virtual camera defines the perspective from which you view your scene. You can position and adjust the camera to zoom in, zoom out, or explore different angles within your 3D world.

    • To make our camera dynamic and allow canvas exploration, we are going to leverage the client's OrbitControls component. Below are our examples. You will see that we just include the component in our canvas, and it just works.
  4. Objects: These actors bring your scene to life. They can be anything from simple geometric shapes like spheres and cubes to complex models like characters or buildings. You create the visual elements that tell your story by manipulating and animating these objects.

Starting from the beginning: to create our Scene with TresJS we just need to use our component TresCanvas in our Vue component's template:

<script lang="ts" setup>  
import { TresCanvas } from '@tresjs/core'  
</script>  
<template>  
	<TresCanvas window-size>  
	<!-- Your scene goes here -->  
	</TresCanvas>  
</template>

The TresCanvas component is going to do some setup work behind the scenes:

  • It creates a WebGLRenderer that automatically updates every frame.
  • It sets the render loop to be called on every frame based on the browser refresh rate.

Using the window-size property, we force the canvas to take the width and height of our full window.

So with TresCanvas component we have created our Renderer and our Scene.

Let's move to the Camera:

<script lang="ts" setup>  
import { TresCanvas } from '@tresjs/core'  
</script>  
<template>  
	<TresCanvas window-size>  
		<TresPerspectiveCamera /> 
	</TresCanvas>  
</template>

We just have to add the TresPerspectiveCamera component to our scene.

NOTE: It's important that all scene-related components live between the TresCanvas component.

Now, only the main actor is missing, let's add some styles and our object inside the scene. Our Vue component will now look like:

<script  setup  lang="ts">
import  { TresCanvas }  from  '@tresjs/core';
import { OrbitControls } from@tresjs/cientos’;
</script>

<template>
<TresCanvas clearColor='midnightblue' window-size>
	<OrbitControls/>
	<TresPerspectiveCamera />
	<TresMesh>
		<TresBoxGeometry  :args="[1,  1,  1]" />
	</TresMesh>
</TresCanvas>
</template>

And our scene will be:

A Mesh is a basic scene object in three.js, and it's used to hold the geometry and the material needed to represent a shape in 3D space.

As we can see, we can achieve the same with TresJS using the TresMesh component, and between the default slots, we are just passing our object (a Box in our example).

One interesting thing to notice is that we don't need to import anything. That's because TresJS automatically generates a Vue Component based on the three objects you want to use in PascalCase with a Tres prefix.

Now, if we want to add some color to our object the Three.js Material class comes to help us. We need to add:

<script  setup  lang="ts">
import  { TresCanvas }  from  '@tresjs/core';
import { OrbitControls } from@tresjs/cientos’;
</script>

<template>
<TresCanvas clearColor='midnightblue' window-size>
<OrbitControls/>
	<TresPerspectiveCamera />
	<TresMesh>
		<TresBoxGeometry  :args="[1,  1,  1]" />
		<TresMeshBasicMaterial  :color="'#DC143C'"  :transparent="true"  :opacity="0.25" />
	</TresMesh>
</TresCanvas>
</template>

Conclusion

Tres.js not only supercharges Vue.js applications with stunning 3D graphics, but it also integrates seamlessly with Nuxt.js, enabling you to harness the performance benefits of server-side rendering (SSR) for your 3D creations. This opens the door to building exceptional web experiences that are both interactive and performant.

With Tres.js, Vue.js developers can leverage a declarative approach, cutting-edge features, and a vast ecosystem to bring their immersive web visions to life. If you want to elevate your Vue.js projects with a new dimension, Tres.js is an excellent choice to explore.

About the author

Mattia Magi

Mattia Magi

Senior Software Engineer

Keep reading

View all posts →

3 VueJS Component Libraries Perfect for Beginners

For developers checking out VueJS for the first time, the initial steps are overwhelming, particularly when setting up projects from square one. But don’t worry! The VueJS ecosystem offers a plethora of remarkable component libraries, easing this early obstacle. These three libraries are pre built toolkits, providing beginners with the means to kickstart their VueJS projects effortlessly. Let’s take a look! Quasar Quasar is among the most popular open source component libraries for Vue.js, offering a comprehensive set of ready to use UI components and tools for building responsive web applications and websites. Designed with performance, flexibility, and ease of use in mind, Quasar provides developers with a wide range of customizable components, such as buttons, forms, dialogs, and layouts, along with built in support for themes, internationalization, and accessibility. With its extensive documentation, active community support, and seamless integration with Vue CLI and Vuex, Quasar empowers developers to rapidly prototype and develop high quality Vue.js applications for various platforms, including desktop, mobile, and PWA (Progressive Web Apps). PrimeVue PrimeVue is a popular Vue.js component library offering a wide range of customizable UI components designed for modern web applications. Developed by PrimeTek, it follows Material Design guidelines, ensuring responsiveness and accessibility across devices. With features like theming, internationalization, and advanced functionalities such as lazy loading and drag and drop, PrimeVue provides developers with the tools to create elegant and high performing Vue.js applications efficiently. Supported by clear documentation, demos, and an active community, PrimeVue is an excellent choice for developers seeking to streamline their development process and deliver polished user experiences. Vuetify Vuetify is a powerful Vue.js component library that empowers developers to create elegant and responsive user interfaces with ease. Built according to Google's Material Design guidelines, Vuetify offers a vast collection of customizable UI components, ranging from buttons and cards to navigation bars and data tables. Its comprehensive set of features includes themes, typography, layout grids, and advanced components like dialogues and sliders, enabling developers to quickly build modern web applications that look and feel polished. With extensive documentation, active community support, and ongoing development, Vuetify remains a top choice for Vue.js developers seeking to streamline their workflow and deliver visually stunning user experiences. For newcomers venturing into Vue.js, the initial setup might seem daunting. Thankfully, Vue.js offers a variety of component libraries to simplify this process. Quasar, PrimeVue, and Vuetify are standout options, each providing pre built tools to kickstart projects smoothly. Whether you prefer Quasar's extensive UI components, PrimeVue's Material Design inspired features, or Vuetify's responsive interfaces, these libraries cater to diverse preferences and project requirements. With their clear documentation and active communities, these libraries empower developers to start Vue.js projects confidently and efficiently, enabling Vue developers to create polished user experiences....

2 mins
VuetifyVueQuasar

Understanding Vue.js's <Suspense> and Async Components

In this blog post, we will delve into how <Suspense> and async components work, their benefits, and practical implementation strategies to make your Vue.js applications more efficient and user-friendly...

Jesús Padrón6 mins
VueWeb PerformanceUXJavaScript

Getting started with Vitepress

Create your static blog site using Vitepress. Setup and configure your site in minutes by following this step-by-step tutorial....

Simone Cuomo12 mins
VueViteVitepress

Nuxt DevTools v1.0: Redefining the Developer Experience Beyond Conventional Tools

Nuxt DevTools v1.0 is a game-changer for web developers, featuring integrated VS Code, real-time views, and a customizable UI. This new toolset enhances efficiency, revolutionizing web development....

Jesús Padrón8 mins
VueNuxtJSDevToolsJavaScript