What is the best way to incorporate a line into a scene using three.js?

I am facing an issue with adding a line in three.js. When I call the addline function in my code, the line doesn't appear in the scene. I have tried to implement the MVC design pattern, but I am unsure where I went wrong. Thank you for any assistance provided.
My code snippet is as follows:

function View(viewArea) {
    var viewport = document.getElementById(viewArea);
    var viewportHeight = document.getElementById(viewArea).offsetHeight;
    var viewportWidth = document.getElementById(viewArea).offsetWidth;

    var renderer = new THREE.WebGLRenderer();
    renderer.setSize( viewportWidth, viewportHeight );
    viewport.appendChild(renderer.domElement);

    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera( 75, viewportWidth / viewportHeight, 0.1, 1000 );
    camera.position.set(100,70,3000);
    camera.lookAt(new THREE.Vector3(0, 0, 0));

    var light = new THREE.PointLight(0xffffff);
    light.position.set(100,100,100);
    scene.add(light);

    this.scene = scene;
    this.camera = camera;
    this.light = light;
    this.renderer = renderer;
}

View.prototype.addLine = function (geometry) {
    var material = new THREE.LineBasicMaterial({ color: 0x000000 });
    var line = new THREE.Line( geometry, material );
    this.scene.add( line );
};

View.prototype.render = function () {
    this.renderer.render(this.scene, this.camera);
};

function Controller(viewArea) {
    var view = new View(viewArea);

    var geometry = new THREE.Geometry();
    geometry.vertices.push( new THREE.Vector3( 0, 0, 0) );
    for(var i=0;i<100;i+=10){
        geometry.vertices.push(
            new THREE.Vector3(i,i+10,i+20)
        );
        view.addLine(geometry);
    }
    view.render();
}

The HTML code snippet is:

<body>
        <div class="container-fluid">
            <div class="row">
                <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2" id="leftMenu">
                </div>
                <div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">
                    <div class="row" id="viewport">
                    </div>
                    <div class="row" id="informationMenu">
                    </div>
                </div>
                <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2" id="rightMenu">
                </div>
            </div>
        </div;

    <script type="text/javascript">
        $(document).ready(function(){
             var controller = new Controller('viewport');
        });   
    </script>
</body>

Answer №1

You are facing two issues with your current setup:

  • Your line is blending in with the background because they are both black
  • Your camera is positioned too far away, causing the line to disappear

To fix these problems, make the following adjustments in your code:

To ensure that your line is visible, adjust your camera settings:

var camera = new THREE.PerspectiveCamera( 75, viewportWidth / viewportHeight, 0.1, 5000 );

To change the color of your line to pink, update the following line:

var material = new THREE.LineBasicMaterial({ color: 0xff00ff });

These changes should resolve the issues you are experiencing. I hope this solution works for you.

Additionally, consider optimizing your code by adding the line geometry to your scene only once. Move the view.addLine(geometry) outside of the loop.

function Controller(viewArea) {
    var view = new View(viewArea);

    var geometry = new THREE.Geometry();
    geometry.vertices.push( new THREE.Vector3( 0, 0, 0) );
    for(var i=0;i<100;i+=10){
        geometry.vertices.push(
            new THREE.Vector3(i,i+10,i+20)
        );
    }

    view.addLine(geometry);
    view.render();
}

For a live example, check out this working pen: http://codepen.io/BBlanchard/pen/RKdNoO

Answer №2

Try implementing something similar to this as it provides a basic example to help you understand.

var renderer, scene, camera, controls;
var geometry, material, line, vertices;
initialize();

function initialize() {
  document.body.style.cssText = 'margin: 0; overflow: hidden;';
  renderer = new THREE.WebGLRenderer({
    alpha: 1,
    antialias: true,
    clearColor: 0xffffff
  });
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 1, 1000);
  camera.position.set(5, 5, 5);
  controls = new THREE.OrbitControls(camera, renderer.domElement);

  material = new THREE.LineBasicMaterial({
    color: 0x0077ff
  });
  geometry = new THREE.Geometry();
  geometry.vertices.push(new THREE.Vector3(0, 0, 0));

  line = new THREE.Line(geometry, material)

  scene.add(line);
  addLine(); // add line
}

function addLine() {
  vertices = geometry.vertices;
 for(var i=0;i<100;i+=10){
     vertices.push(new THREE.Vector3(i,i+10,i+20));
     }
  geometry = new THREE.Geometry();
  geometry.vertices = vertices;
  scene.remove(line);
  line = new THREE.Line(geometry, material)
  scene.add(line);
  renderer.render(scene, camera);
}
<script src=http://mrdoob.github.io/three.js/build/three.min.js></script>
<script src=http://mrdoob.github.io/three.js/examples/js/controls/OrbitControls.js></script>

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

Developing an Angular filter using pipes and mapping techniques

I am relatively new to working with Angular and I have encountered a challenge in creating a filter for a specific value. Within my component, I have the following: myData$: Observable<MyInterface> The interface structure is outlined below: export ...

The Countdown Timer in React Native triggers an error due to Invariant Violation

According to some expert advice from this stackoverflow answer, I attempted to implement a countdown timer for my project as shown below. constructor(props: Object) { super(props); this.state ={ timer: 3,hideTimer:false} } componentDidMount(){ this. ...

Unable to make a div grow within a Popper component in a React.js application

I'm facing a challenge with implementing a CSS feature and need some assistance. https://i.stack.imgur.com/KXpGd.png Upon clicking the "See link options" button, the content loads but spills out of the popper. My goal is to have the popper expand in ...

Utilizing JQuery and Jade to extract and display information from a Node.js server

I am currently working with the Jade framework for frontend and using Node.js & express for backend development. When rendering a view with data, I am encountering an issue where I can't access this data using JQuery. Below is my service in Node.js ...

I encountered an issue in reactjs where I received the error message: TypeError: this.state.coords.map is not functioning properly

Here is the code snippet I wrote: import React, { Component } from 'react'; class LocationApp extends Component { constructor(props){ super(props) this.state = { coords:[], error:[], } } ...

Violation of Content Security Policy directive has occurred

During my full-stack project development, I encountered an issue with the inclusion of the bundle.js file in my base HTML file using a simple script tag. When trying to render the page and utilize the JS functionality, I faced a content security policy vio ...

Using Angular 2 to execute an interface while making an HTTP GET request

I've managed to successfully retrieve and display data from a JSON object using *ngFor in Angular. However, I am struggling with applying an interface to the retrieved data. This is the content of my interface file: import {Offer} from './offer ...

Developing a universally accessible variable for utilization in various functions

I'm having trouble understanding why 'currentPos.LatLng' is undefined when trying to access it outside the function even though it's part of an object. I want to be able to retrieve the current position values to use them in another fun ...

Accessing each element within a Next.js application through a personalized hook during page load

Within my Next.js application, I have implemented a React hook that retrieves the currently authenticated user and stores it in global state. I am looking to execute this hook once on page load while making it accessible to every component within the app. ...

Having trouble importing cubing.js into my discord bot running on node

When attempting to import the cubing.js module into my nodejs project for use in a discord.js bot, I encountered an error. The specific import causing issues was const {randomScrambleForEvent } = require('cubing/scramble'), resulting in 'Err ...

The Shopify Pixel Extension has encountered an issue - error code 1

Looking to develop a web pixel extension for my Shopify app, I followed the official guide: While building the app, encountered this error: extensions | my-app-pixel (C:\projects\shopify\my-app-pixel\node_modules\.bin\shopify ...

Managing the "Accept Cookies" notification using Selenium in JavaScript

As I use Selenium to log in and send messages on a specific website, I am faced with a cookie popup that appears each time. Unfortunately, clicking the accept button to proceed seems to be quite challenging for me. Here is an image of the cookie popup Th ...

Approach for checking duplicates or empty input fields through PHP, AJAX, and JavaScript

Looking for a solution to validate and check for duplicate values when listing, creating, or deleting products using a REST API. I tried using rowCount in the php file to check for duplicates but I feel there might be a better approach that I am missing. N ...

Resizing nested elements while maintaining consistent padding dimensions

If you're looking to create a sleek foundation for a 200px wide, 30px high editable combobox that can be easily used with angular binding or other JavaScript data-binding solutions, consider the following HTML code. However, there's a desire to m ...

Text located in the bottom right corner of the window with the use of JavaScript

Is there a way to replace text at the bottom right of the window, as opposed to the page, so that it remains fixed in the corner of the window? I'm looking to create a "share" link that is always visible. ...

Having difficulty incorporating TypeScript into Vue

A little while ago, I set up a vue project using vue init webpack . and everything was running smoothly. Recently, I decided to incorporate typescript and ts-loader. I created a file in the src directory with the following content: declare module '* ...

What could be causing the empty object return from the Async function in my Typescript code on Next JS?

Encountering issues with an async function. In the ../lib folder, I have a class for handling data from an API website. However, when attempting to load the API data within an async function, I encounter difficulties. The async function does not return a ...

Map checkboxes aren't updating after an array update following a refactor to react hooks

I recently transformed a class component into a function component using hooks. However, I am facing an issue where the checkboxes within a specific mapping are not updating with the checked value. The onChange handler is firing and updating the array corr ...

What is the best way to load $cookies into an Angular service?

After defining an Angular service where I need to access a cookie, I noticed that the $cookieStore is deprecated and that it's recommended to use $cookies instead. This is how my service is set up: 'use strict'; var lunchrServices = angul ...

Steps to ensure a variable remains constant across a controller, JS file, and a rendered partial

I am working on rendering a partial viewer using ajax and jQuery. My goal is to assign a variable within the partial based on the link that is clicked. Here is the ERB code: <%=link_to "link1", viewer_path(id: Painting.first), remote: true%> <%= ...