Update the line material in three.js dynamically during runtime

Having a Line object with THREE.LineBasicMaterial, I attempted to update the material:

material = new THREE.LineDashedMaterial({
    dashSize: 5,
    gapSize: 5,
  })

  line.material = material

  line.material.needsUpdate = true
  line.geometry.uvsNeedUpdate = true
  line.geometry.verticesNeedUpdate = true

  line.computeLineDistances()

Unfortunately, despite these changes, the line remains undotted. Any suggestions on how to achieve the desired effect?

Answer №1

This code functions as intended:

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);
camera.position.set(3, 5, 8);
const renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

const controls = new THREE.OrbitControls(camera, renderer.domElement);

scene.add(new THREE.GridHelper(10, 10));

const points = [];
const pointsCount = 10;
for (let i = 0; i < pointsCount; i++) {
  points.push(new THREE.Vector3(
    Math.random() - 0.5,
    Math.random() - 0.5,
    Math.random() - 0.5
  ).multiplyScalar(10));
}
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
  color: "yellow"
});
const line = new THREE.Line(geometry, material);
scene.add(line);

btnDashed.addEventListener("click", event => {
  const dashMaterial = new THREE.LineDashedMaterial({
    color: (Math.random() * 0x888888) + 0x888888,
    dashSize: 0.5 + Math.random() * 0.5,
    gapSize: Math.random() * 0.5
  });
  line.computeLineDistances();
  line.material = dashMaterial;
});

renderer.setAnimationLoop(() => {
  renderer.render(scene, camera)
});
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<button id="btnDashed" style="position: absolute;">
Make dashed
</button>

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

An error occurred: Cannot access the 'splice' property of an undefined value

//Screenshot <div v-for='(place) in query.visitPlaces' :key="place.name"> <div class="column is-4 is-narrow"> <b-field label="Nights"> <b-input type="text" v-model="place.nights" placeho ...

Storing socket.io data in an array

Having trouble getting the desired array of arrays from my socket.io emitter. The structure I need is: [ [{...},{...},{...}] , [{...},{...}] , [{...}] ] But instead, I am receiving a different format. https://i.stack.imgur.com/3PY0u.jpg I require all t ...

Can you explain the significance of the visitFunction error message?

When running [email protected] + [email protected] + [email protected] + [email protected], I encountered an error message. Can anyone help me understand what this error means? I am simply executing: res.render(view, response); Proper ...

I'm having trouble loading a GLB 3D model in Three.js

Having trouble loading a GLB 3D model using threejs? Despite following the steps in the documentation, the model fails to load. import * as THREE from './node_modules/three/src/Three.js'; import { GLTFLoader } from './node_modules/three/exam ...

Unexpected button behavior sparked by Vue.js

Check out this fiddle I created: https://jsfiddle.net/frvuw35k/ <div id="app"> <h2>Vue Event Test</h2> <form @submit.prevent> <div class="form-group row"> <div class="col-sm-12 i ...

How can I create a real-time page update using node.js?

I am completely new to node.js, but my main goal in learning this language is to achieve a specific task. I want to create a webpage where the content within a designated "div" can be swapped dynamically for users currently viewing the page. For example, ...

Adding a method to a subclass of Array is not allowed

I'm trying to create a subclass of the Array object using the following code. It works perfectly when running in the browser. However, if I save this code in a .js file and include it with a <script> tag, the .add() method becomes undefined. ...

A highly effective method for nesting items within a list through recursive functions

I am currently in the process of developing my own commenting system because I have found that existing platforms like Disqus do not meet my specific needs. My backend is built using NodeJS and MongoDB, and I need to execute two primary queries on my data ...

The MVC 5 view is unable to display an HTML image when adding it within an appended div

Currently, I am working with ASP.net MVC5 at a novice level. I'm faced with the challenge of creating a div that displays an image using a JavaScript function. Here is the code snippet I have: function showLoadingImage() { $('#submit_Em ...

Encountering the React.Children.only error while trying to use the <Link> component in Next.js

I'm encountering an issue with the code below: Error: React.Children.only expected to receive a single React element child. While trying to troubleshoot, I noticed that it only allows me to have one header under the link. <div className="co ...

Is it possible to dynamically alter a CSS property using styled components when an onClick event occurs?

Hey there, I'm pretty new to React and currently exploring styled components for the CSS styling of my components. One of the components I've created is a button called SummonButton: const SummonButton = styled.button` height: 50px; borde ...

The jQuery script automatically triggers submission on its own

Does anyone have an idea why the form auto-submits itself? I can't figure out why it's doing that. I'm using query parsley to validate the form in a modal. When a user opens the modal and starts typing in the text area, they must type at l ...

Can you explain the distinction between the two methods of coding in jQuery?

1, $.each(a,f); 2,$("a").each(f); I understand the purpose of the last line, where it selects all <a> elements in the document and then calls the each() method to invoke function f for each selected element. However, I am unsure about the meani ...

Obtaining a response in string format using the $.ajax function

var module = (function(){ return{ loadData: function(url, success, error){ $.when($.ajax({ type: 'GET', cache: false, url: url, contentType: 'application ...

CSS magic: Text animation letter by letter

I have a <div> with text. <div> to be revealed on the page one character at a time:</p> <div>, the animation should stop and display the full text instantly.</p> In summary, I aim to replicate an effect commonly seen in Jap ...

Copy and paste the code from your clipboard into various input fields

I have been searching for a Vanilla JavaScript solution to copy and paste code into multiple input fields. Although I have found solutions on the internet, they are all jQuery-based. Here is an example of such a jQuery solution <input type="text" maxl ...

Having trouble getting the Html onload function to work in Google Sheets App Script?

I'm working with google sheets and I'm in the process of creating a document to track employees who are currently out of the office. I have added a menu option that allows me to remove employee data, which triggers the opening of a sidebar contai ...

Filter a div based on multiple conditions using JavaScript/jQuery

In my filtering system, I have two sections: place and attraction. When I select a place, the corresponding div is displayed according to the selected place. Similarly, when I select an attraction, only the attractions are filtered accordingly. <ul clas ...

Utilize an array of JSON objects to populate an array of interfaces in Angular/Typescript

I am currently facing a dilemma - my code is functioning without any errors when executed, but my text editor is flagging an issue stating that the property 'categories' does not exist on type 'CategoryInterface[]' (specifically on the ...

Checking React props using Jest and Enzyme - A simple guide

Trying to understand React testing, I came across two files: Button.js and Button.test.js The code below contains the question along with comments: // Button.js import React from 'react'; import { string, bool, func } from 'prop-types&apos ...