How can I incorporate the Three.js scene demonstration into Vue 3?

Looking to integrate the Three.js beginner example for creating a scene [1] into a Vue.js 3 project using JavaScript (not TypeScript)?

[1]

main.js

import * as THREE from 'three';

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );

camera.position.z = 5;

function animate() {
    requestAnimationFrame( animate );

    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;

    renderer.render( scene, camera );
}

animate();

index.html

<!DOCTYPE html>
<html>
    <head lang="en">
        <meta charset="utf-8">
        <title>My first three.js app</title>
        <style>
            body { margin: 0; }
        </style>
    </head>
    <body>
        <script type="module" src="/main.js"></script>
    </body>
</html>

Answer №1

For those on a quest, here is a helpful response. Thankfully, there are online communities where individuals are more welcoming towards valid inquiries [1].

App.vue

<script setup>
import { ref, onMounted } from 'vue';
import * as THREE from 'three';

const target = ref();

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

const renderer = new THREE.WebGLRenderer();
renderer.setSize(500, 500);

const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

function animate() {
  requestAnimationFrame(animate);

  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;

  renderer.render(scene, camera);
}

onMounted(() => {
  target.value.appendChild(renderer.domElement);
  animate();
});
</script>

<template>
  <div ref="target"></div>
</template>

[1] https://github.com/vuejs/core/discussions/9057

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to calculate the total number of rows in a datatable

I have implemented a datatable in my project, and I need to find out the total number of rows in the table when it is loaded. Here's the snippet of code I am currently using: $(document).ready( function() { $('#jobSearchResultTable').data ...

What is the best way to implement a required input field in Vue.js?

I need some assistance with my chat functionality. I want to prevent users from sending empty messages, so I want to make the input field required. Can you please help me with this? I have already tried adding "required='required'" to the input ...

Strange error message regarding ES6 promises that is difficult to interpret

Snippet getToken(authCode: string): Promise<Token> { return fetch(tokenUrl, { method: "POST" }).then(res => res.json()).then(json => { if (json["error"]) { return Promise.reject(json); } return new Token ...

The functionality of RegExp is not as expected in this specific case, even though it works correctly in all

I am new to Node.js and currently transitioning from a PHP background, eager to learn more about it. My challenge involves using the following Regular Expression: /([A-Z]{2,})+/gim (identifying two or more consecutive letters). The string I am working w ...

What is the method for including the `meta:redirect` or `<meta http-equiv="refresh" content="0; url=http://example.com" />` in the metadata object for Next.js version 13?

In order to redirect users from one of my pages, I previously utilized the redirect metatag. However, I am unable to locate similar options within the metadata API in Next.js 13 for the appRouter. ...

Customize material-ui themes using useStyles / jss

Is it possible to customize the Material-UI theme using styles without relying on !important? const customTheme = createMuiTheme({ overrides: { MuiInputBase: { input: { background: '#dd7711', padding: 10, }, ...

Issue encountered when running a minification build on Angular 5

After successfully updating my Single Page Application (SPA) from Angular 4 to Angular 5 along with all dependencies, everything seemed to be working well. Both the development and production builds were functioning without any errors or warnings. However ...

How do I identify whether a link from the API is a Nuxt link with :to or :href?

Currently, I am constructing my main menu using data from an API: <b-navbar-nav> <div v-for="result in resultsmenu" :key="result.id"> <span class="hoverlink"> <nuxt-link :to="result. ...

Steps to troubleshoot the TypeError: cv.Mat is not a constructor in opencv.js issue

Encountering a problem while trying to use opencv.js for detecting aruco markers from my camera. Each time I attempt to utilize the method let image = new cv.imread('img'); An error keeps popping up: TypeError: cv.Mat is not a constructor ...

The AJAX request to the REST service is failing to trigger the success function in the AJAX call

Struggling with some issues related to AJAX, specifically when calling a Java REST server that I've developed. While I am relatively new to AJAX, I have put in quite a bit of effort searching for solutions. The problem arises when making a call from a ...

What is the best way to split an array into smaller chunks?

My JavaScript program fetches this array via ajax every second, but the response time for each request is around 3 to 4 seconds. To address this delay, I attempted to split the array into chunks, however, encountered difficulties in completing the task: { ...

Implementing state management in ReactJS

I'm a newcomer to ReactJS and I've encountered an issue with the setState function in my code. The expectation was for the value to increment by 1 every second, but that isn't happening. import React from 'react'; import ReactDOM ...

Exploring a JavaScript file with the power of JavaScript and HTML

I have a .js file that contains the following data (excerpt for brevity) var albums= "tracks":[ {"title":"Dunnock","mp3":"Birdsong-Dunnock.mp3", "lyrics":"The Dunnock or hedge sparrow has a fast warbling song often delivered from t ...

Tips for creating a responsive iframe without relying on aspect ratio assumptions

Is there a way to create a responsive iframe without relying on a fixed aspect ratio? The width and height of the content are unknown until rendering. Keep in mind, using Javascript is an option. For instance: <div id="iframe-container"> <i ...

Different ways to maintain the original syntax highlighting colors in JavaScript console

Upon closer inspection near the green arrows, you can see that the default console.log function colorizes values based on their type, distinguishing between string and number. https://i.sstatic.net/MtO8l.png In contrast, highlighted near the red arrows i ...

What is the proper way to document instance members that have been added through Object.defineProperties()?

I am struggling with JSDoc 3 recognizing instance properties defined using Object.defineProperties in my class. Here is a simplified version of the code I am working on: /** @exports mymodule */ function mymodule(exports) { /** @constructor * @p ...

Utilizing Laravel 6 alongside Vue.js and webpack in place of the traditional Vue implementation

Starting a new Laravel project, I used the composer create-project --prefer-dist laravel/laravel FullStack command to set it up. Next, I included Vue.js with the composer require laravel/ui command, followed by running npm install and npm run dev. Expecti ...

Value of type 'string' cannot be assigned to type '{ model: { nodes: []; links: []; }; }'

I am a beginner in TypeScript and I have added types to my project. However, I am encountering an error with one of the types related to the graph: Type 'string' is not assignable to type '{ model: { nodes: []; links: []; }; }'.ts(2322) ...

Customize AngularJS dropdown options using a constant value for filtering

How do I display drop-down options based on the Json object below where IsDeleted == 0 "currencies":[{ "CurrencyID":"1", "CurrencyCode":"AED", "CurrencyName":"United Arab Emirates Dirham", "IsDeleted":"1" },{ "CurrencyID":"2", "C ...

Ways to merge several getServerSideProps functions

Within my project, I have two important pages: index.js and other.js. In index.js, there exists a crucial method known as getServerSideProps: export async function getServerSideProps(context) { //code here } The challenge arises when I realize that I ...