Tips for resizing a two-dimensional circle using a small graphical user interface in THREE.js

My goal is to adjust the size of a circle by dragging a small GUI slider. I've developed this code which creates a circular shape with a blue outline on a black background using an orthographic camera:

    setUpGUI();
    let radius = 0.6;
    let vertices = [];
    for(let i = 0; i <= 360; i++){
        vertices.push(new THREE.Vector3(Math.sin(i*(Math.PI/180))*radius, Math.cos(i*(Math.PI/180))*radius, 0));
    }

    let geometry = new THREE.BufferGeometry().setFromPoints(vertices);

    let material = new THREE.LineBasicMaterial({color:"blue"})
    var lineStrip = new THREE.Line( geometry, material );

In addition, I have created a setUpGUI() function that adds a slider to adjust the controls.radius value:

function setUpGUI() {

    controls =  {   radius  : 0.6
                };

    gui.add( controls, 'radius', 0.1, 0.7).onChange(value => updateRadius(value));
    gui.open();
};

The onChange method triggers the updateRadius function and passes the new radius value as an argument:

function updateRadius(value) {
    radius = value;
    var vertices = [];
    for(let i = 0; i <= 360; i++){
        vertices.push(new THREE.Vector3(Math.sin(i*(Math.PI/180))*radius, Math.cos(i*(Math.PI/180))*radius, 0));
    }
    renderer.clear();
    renderer.render(scene, camera);
}

However, there seems to be an issue with this code as it displays an error message saying "renderer is not defined". I attempted to resolve this by passing the renderer as a function parameter, but then encountered similar errors related to "scene" and "camera". I even included scene and camera as parameters in the function, but unfortunately, the circle still did not change its size.

Answer №1

If you're looking for an alternative to what @prisoner849 suggested, which involves creating a circle with a radius of 1 and then scaling it, you can utilize the following code snippet to modify the geometry. It seems like this aligns more with your original intention.

import * as THREE from 'three';

import { GUI } from 'three/addons/libs/lil-gui.module.min.js';

let camera, scene, renderer;

let lineStrip;

const params = {
    radius: 0.6
};

init();
render();

function init() {

    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
    camera.position.z = 1;

    scene = new THREE.Scene();

    const radius = params.radius;
    const vertices = [];

    for ( let i = 0; i <= 360; i ++ ) {

        vertices.push( new THREE.Vector3( Math.sin( i * ( Math.PI / 180 ) ) * radius, Math.cos( i * ( Math.PI / 180 ) ) * radius, 0 ) );

    }

    const geometry = new THREE.BufferGeometry().setFromPoints( vertices );
    const material = new THREE.LineBasicMaterial( { color: 'blue' } );

    lineStrip = new THREE.Line( geometry, material );
    scene.add( lineStrip );

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    const gui = new GUI( { width: 300 } );

    gui.add( params, 'radius', 0.1, 2 ).onChange( changeRadius );
    gui.open();

}

function render() {

    renderer.render( scene, camera );

}

function changeRadius() {

    const positionAttribute = lineStrip.geometry.getAttribute( 'position' );
    const radius = params.radius;

    for ( let i = 0; i <= 360; i ++ ) {

        const x = Math.sin( i * ( Math.PI / 180 ) ) * radius;
        const y = Math.cos( i * ( Math.PI / 180 ) ) * radius;
        const z = 0;

        positionAttribute.setXYZ( i, x, y, z );

    }

    positionAttribute.needsUpdate = true;

    render();

}

It's important to note that simply updating the vertices array is not enough. You must also update the buffer attribute accordingly.

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

A duo creating art on a shared canvas

I have encountered an issue while developing a real-time paint app using HTML5 canvas. Everything works fine when a single user is drawing on the canvas, but problems arise when two users try to draw simultaneously. For example, if one user changes the col ...

Utilize React JS to dynamically render JSON array of images onto a JSX page in React

state = { products: [ { img: "'./images/heartstud.jpg'", name: "Heart Earrings", price: "1.99", total: "3.98", count: 2, description: "Yellow Chimes Crystals from Classic Designer Gold Plated Styl ...

What is the process for incorporating items from Slick Grid into a Multi Select TextBox?

Exploring the world of Slick Grid for the first time. Here is where I define my variables in JavaScript. var grid; var printPlugin; var dataView; var data = []; var selectdItems = []; var columns = [ { id: "Id", name: "Id", field: "Id", sortable: t ...

Counting the elements on a page using Selenium and Node.js: A step-by-step guide

I've been experimenting with Selenium in Javascript using NodeJS and I'm trying to tally up some elements based on CSS selectors. So far, I've attempted a few methods: client.findElements(By.css(".some-class")).size(); However, I encounte ...

The close button on bootstrapselect is oversized

Having an issue with implementing the bootstrap select search and close button in my view. An image has been uploaded through the following link: View the bootstrap select dropdown image here Javascript $('#class_list_for_fee_report').multisel ...

One Background Image Serving Multiple Divs

Can you use one image (PNG or SVG) as the background for multiple divs? Take a look at the images below to see how it could work. And if the screen width gets smaller and the divs stack up vertically, is there a way to change the background accordingly? D ...

Getting the Angular component class reference within a triggered Highcharts selection event callback - what's the best approach?

It seems like I'm facing a common javascript closure issue, but let me illustrate it with a specific example as I'm struggling to grasp it in an Angular context. In my Angular component, I'm using the Highcharts library to visualize data. W ...

Troubleshooting issue in Laravel9 where DB Query is not properly summing values of one parent and 2 children in selectraw

Currently, I am working with 3 tables: invoices, coletes, and incasaris. Invoices ID Coletes ID Invoice_id totaleuro Incasaris ID Invoice_id i_totaleuro 1 1 1 200 1 1 200 ...

What is the process for applying a class in jQuery to empty HTML elements?

Working on a WordPress/PHP website and looking to dynamically add a class when child elements are empty? This is the HTML structure: <div class="featured-block"> <a href="/" class="featured-block__item cf"> <div class="featured-bl ...

It vanishes as soon as you move your cursor away during the animation

I created a button component with text animation, but I'm encountering an issue. When I hover over the button, the animation works smoothly. However, if I quickly move my cursor away or unhover in the middle of the animation, the text disappears unex ...

Utilization of traditional techniques across various Vue components

Can you guide me on the correct usage of the method isValidEmail in compA.vue and other potential compB.vue? The following method does not seem to be effective for me: <template> <div></div> </template> <script> export de ...

TypeScript incorporates a variety of @types versions for react

I made changes to my compilerOptions within the tsconfig.json file with the specified paths "paths": { "react": ["node_modules/@types/react"], "@types/react": ["node_modules/@types/react"] } However, I noticed that @types/react-router is using its o ...

Click handler that transmits data to a server using ajax

I have been tasked with creating a website using HTML, CSS, and JavaScript that includes three buttons. When clicked, these buttons will send codes such as "10," "01," and "11" to a C++ program. The C++ program will then respond and perform a function base ...

Error Alert: The function findByID is not recognized in this context (Node.js)

I currently have two distinct directories. /controller/anbieter.js function getAnbieterById(req, res) { var userid = parseInt(req.params.id); let anbieter = Anbieter.findById(userid); res.send(anbieter); }; /model/anbieter.js ...

Error: The jQuery TableSorter Plugin is unable to access property '1' as it is undefined

I've been attempting to utilize the jquery table sorter plugin, but I keep encountering an error when trying to sort the table. The error message I'm receiving is: cannot read property '1' of undefined This is the HTML code I have: ...

One login for accessing multiple forms

I am trying to figure out a way to use one login for two different forms that serve different functions. How can I pass the login details between these two functions? Just to clarify, I only have knowledge of JavaScript and VBScript, not jQuery. For inst ...

What steps can I take to ensure that my progress bar updates and loads automatically?

My progress bar only starts working when clicked, and it doesn't refresh automatically. Is there a way to make it refresh and load automatically without requiring user interaction? Here is the code that I am currently using. Any help would be greatly ...

Tutorial on implementing a _variables.scss file for Vue components with sass-resource-loader on Vue CLI 3.04

In my VueJs project created with the Vue CLI 3.0.4, I am aiming to utilize SCSS variables across all components without the need to import _variables.scss into each one individually. After some research, I found that I can achieve this using sass-resource- ...

Is it feasible to retrieve the name of an object from an array where it is stored?

Context: The data structure provided below makes it easy to access individual items and their properties. For instance, retrieving the value Volkswagon is a simple task. let car = {}; let truck = {}; car.one = 'Volkswagon'; car.two = 'Toyo ...

Steps for making a Trello card via a Discord bot

As a beginner in Java script coding, I am attempting to create a bot for adding a card to my Trello board. Despite hours of searching online, I have not been able to find a solution. if(isCommand('gameban', message)){ if(!message.membe ...