What could be the reason for the three.js scene failing to render in my Svelte application?

Scene.svelte

<!-- Start by binding a container, then add the renderer to this container onMount -->
<script>
    import { onMount } from 'svelte';
    import * as THREE from 'three';
    let container;
    onMount(async () => {
        const scene = new THREE.Scene();
        const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000);

        const renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setPixelRatio(window.devicePixelRatio);
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.toneMapping = THREE.ACESFilmicToneMapping;
        renderer.toneMappingExposure = 1;
        renderer.outputEncoding = THREE.sRGBEncoding;
        container.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;
    });
</script>

<div id="container" bind:this={container}/>

App.svelte

<script>
  import { onMount, onDestroy } from "svelte";
  import Navbar from './components/Navbar.svelte';
  import Hero from "./components/Hero.svelte";
  import Content from "./components/Content.svelte";
  import About from "./components/About.svelte";
  import Work from "./components/Work.svelte";
  import Projects from "./components/Projects.svelte";
  import Accordion from "./components/Accordion.svelte";
  import Skills from "./components/Skills.svelte";
  import Experience from "./components/Experience.svelte";
  import Contact from "./components/Contact.svelte";

  import Scene from "./components/Scene.svelte";

  import './assets/stylesheets/content.css';
  import './assets/stylesheets/navbar-862-and-up.css';
  import './assets/stylesheets/navbar-862-down.css';
</script>


<!-- <Navbar/>
<Content>
  <Hero slot="landing-section"/>
  <About slot="about-section"/>
  <Work slot="work-group-section">
    <Projects slot="projects-section">
      <Accordion slot="accordion-group" repos={included}/>      
    </Projects>
    <Skills slot="skills-section"/>
    
    <Experience slot="exp-section" min_year={min_year} max_year={max_year} on:changeYear={fetch_contribs}/>
  </Work>
  <Contact slot="contact-section" on:sendMail={send_mail}/&>
</Content> -->
<Scene/>

I have simplified some of the code in here. This is my primary App.svelte file with the Scene.svelte file placed within a components folder in the root directory of App.svelte.

I attempted installing threlte initially, but encountered rendering issues which led me to install three.js separately without threlte. Despite trying various approaches like threlte and rendering using a live server or an .html file, nothing seems to be working. Any suggestions on what I should do next?

Answer №1

Don't forget to render your scene:

onMount(() => {
    // ... snip ...
    function animate() {
        requestAnimationFrame(animate);
        renderer.render(scene, camera);
    }
    animate();
});

Here are some additional Svelte tips:

  • Your onMount doesn't need to be asynchronous since there are no await calls.
  • Avoid using IDs in components for reusability. Use bind:this instead of IDs.
  • Avoid importing CSS files globally. Opt for scoped styling and consider using svelte-preprocess for external file handling.

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

Seamlessly transition between various states within a React component for a fluid user experience

I'm currently working on a simple component structured like this: var component = React.createClass({ render: function(){ if (this.props.isCollapsed){ return this.renderCollapsed(); } return this.renderActive() }, ren ...

Does anyone know if it's feasible to return a value from PHP to an HTML form without relying on JavaScript?

Currently, I am in the process of learning how to create a basic web form. My goal is to develop an HTML web form that sends a number to PHP and then displays the number in another text field without refreshing the page. After doing some research online, ...

Consolidate two AJAX requests into a single callback

I'm developing a Chrome extension and facing the challenge of merging two separate AJAX calls into one callback upon success. What would be the most efficient approach to achieve this? Auth.prototype.updateContact = function(id, contact_obj) { var ...

Is it possible to maintain the component's DOM state when navigating away and then returning in Angular?

After spending several days researching this issue, I find myself at a dead end. I thought I was dealing with a common scenario: A user navigates to a specific page, makes some changes (such as editing an input field, scrolling through grid data, or chang ...

"Trouble with Angular's http.get method failing to retrieve data from MySQL through Node

I am struggling to retrieve data from MySQL using Angular and Node.js. Despite trying, I am unable to make it work. When I check Postman using the link http://localhost:8080/locations, I can see the data. { "status": "200", "items": [ { "cit ...

Avoid generating `.d.ts` definition files during the onstorybook build process in a Vite React library project

I am currently developing a component library using react and typescript. I have integrated Vite into my workflow, and every time I build Storybook, the dts plugin is triggered. This has two undesired effects: It generates numerous unnecessary folders an ...

Executing functionality based on changes in Angular bindings

I am working on securing user passwords in my HTML form. Currently, the password field is stored in localstorage like this: In JS: $scope.localStorage = localStorage; And then in HTML: <input id="pass" type="password" ng-model="localStorage.pass" re ...

Sequence of background colors not altering as intended

After clicking a button, I included the following jQuery code in a code snippet on my WordPress site: jQuery("#cf_course_planner tr").css("background-color", "#f66"); jQuery("#cf_course_planner tr:eq(0)").css(& ...

There seems to be an issue with Bookshelfjs and bcrypt hashPassword - it is functioning properly during the create

When using bcrypt to hash passwords in bookshelfjs, I encountered an issue where the password was not being hashed when attempting to update it. Here is the code snippet: model.js var Bookshelf = require('../../db').bookshelf; var bcrypt = requ ...

What is the best way to create a loop using JSON information?

Seeking assistance to create a loop using JSON data to display the title, link, and description of advertisements in HTML format. Provided is a JSON template with two ads, but my actual JSON contains 10-20 IDs. What am I overlooking in the code below? Sto ...

Troubleshooting a Tiny Bottom Sheet Problem in react-native

On my page, I have a bottom sheet that takes up 3/4 of the space. Then, within that bottom sheet, I open another bottom sheet that only occupies 1/4 of the space (without closing the first one). ...

Grids designed in the style of Pinterest

Seeking advice on aligning divs in a Pinterest-style layout. Currently, my setup looks like this: https://i.sstatic.net/erlho.png But I want it to look more like this: https://i.sstatic.net/K9FnD.png Would greatly appreciate any tips or suggestions on ho ...

Is there a way to determine the dimensions of a pdf file using javascript and capture a snapshot of it for showcasing on a website?

I'm fairly new to HTML/CSS and haven't delved into javascript yet, but I have a good understanding of reading other people's code. Currently, I'm putting together my portfolio website and would like to include my resume on the page in a ...

Ensure your HTML5 videos open in fullscreen mode automatically

I managed to trigger a video to play in fullscreen mode when certain events occur, such as a click or keypress, by using the HTML 5 video tag and jQuery. However, I am now looking for a way to have the video automatically open in fullscreen mode when the p ...

Adjust the HTML layout based on the JSON data provided

I am working with a JSON script that contains live matches, which change every 5 minutes. The changes could involve keys such as live_in or score. Matches are also being deleted and added to the JSON. I want to ensure that my HTML output remains updated at ...

Is the initial carousel element failing to set height to 100% upon loading?

If you take a look here, upon loading the page you will notice a DIV at the top. It is labeled "content" with "content_container" wrapped around it and finally, "page" around that. Clicking the bottom left or right arrows reveals other DIVs with similar ta ...

What are the steps for installing the latest version of popper, v2?

When you run the following command: npm install popper.js --save You will receive a warning message that says: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81f1eef1f1e4f3afebf2c1b0afb0b7afb0">[email& ...

Utilize React JS to serialize form data for submission via a POST request

I have a simple form where users input text and it triggers an AJAX request to create a new comment. var CommentForm = React.createClass({ propTypes: { // ... // ... }, handleFormSubmit: function(e) { e.preventDefault(); var compo ...

Using JavaScript parameters in a HTML document

I am trying to replicate a page similar to this. The issue I am facing is the inability to use external JS files in ASP.net (as far as I know). Therefore, I am defining the functions and attempting to utilize them within the HTML page instead. <%@ P ...

What is the purpose of including an es directory in certain npm packages?

Why do developers sometimes have duplicated code in an es folder within libraries? Here are a few examples: https://i.stack.imgur.com/BWF6H.png https://i.stack.imgur.com/3giNC.png ...