Spin a sphere by clicking on a link using three.js

I've designed a spherical object and have a group of links. I'm looking for a way to manipulate the position or rotation of the sphere by simply clicking on one of the links. Despite extensive searching, I haven't been able to find an example that matches this specific criteria.

Answer №1

To add interactivity to your webpage, you can easily create an HTML element and link it to a JavaScript function for the "onclick" event. Below is a quick example using a button (but feel free to use a different element like a link):

HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Rotate Mesh On Button Clicked</title>
    </head>

    <body>

        <button onclick="myFunction()">Rotate</button>


        <script type="text/javascript" src="three.min.js"></script>
        <script type="text/javascript" src="OrbitControls.js"></script>

        <script type="text/javascript" src="scene.js"></script>

    </body>

</html>

JavaScript

 var container, camera, scene, renderer;
 var geometry, material, mesh;

 var cameraControls;

init();
animate();

function init() {

    container = document.createElement( 'div' );
    document.body.appendChild( container );

    // renderer

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setSize( window.innerWidth, window.innerHeight );
    renderer.setClearColor( 0xdbdbdb );
    container.appendChild( renderer.domElement );

    // scene

    scene = new THREE.Scene();

    // camera

    camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 10000 );
    camera.position.set( 3, 0.5, 40 );
    scene.add( camera ); 

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

    // lights

    scene.add( new THREE.AmbientLight( 0x222222 ) );

    var light = new THREE.PointLight( 0xffffff, 0.8 );
    camera.add( light );

    // objects

    geometry = new THREE.CylinderGeometry( 5, 5, 5, 5 );

    material = new THREE.MeshPhongMaterial(  {color: 0x00aafa} );

    mesh = new THREE.Mesh( geometry, material );



    scene.add( mesh );

    window.addEventListener( 'resize', onWindowResize, false );

}

function myFunction() {

    mesh.rotateX(90);
}

function onWindowResize() {

    camera.aspect = window.innerWidth / window.innerHeight;

    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

}

function animate() {

    requestAnimationFrame( animate );

    render();

    cameraControls.update();

}

function render() {

    camera.lookAt( scene.position );

    renderer.render( scene, camera );

}

In this code snippet, clicking the button triggers the "myFunction" which rotates the Mesh by 90°, demonstrating a simple interactive feature.

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

Poor quality picture captured with the use of the getUserMedia() Javascript function

Is there a way to improve the resolution of mobile phone camera screenshots taken with JavaScript's getUserMedia function? if (navigator.mediaDevices) { navigator.mediaDevices.getUserMedia({ video: { width: { min: 1280, }, heig ...

How can I retrieve the number of links pointing to a specific property within a JavaScript object

I am faced with the following dataset: const main = 'test1'; const data = [ { from: 'test1', to: 'test2' }, { from: 'test2', to: 'test3' }, { from: 'test3', to: ...

encountering an issue: file or directory does not exist, unable to open 'rds-combined-ca-bundle.pem'

I recently downloaded AWS secure socket for my Node server and integrated it into my index.js folder. However, I encountered an error that reads: "Error: ENOENT: no such file or directory, open 'rds-combined-ca-bundle.pem'. Could someone help me ...

Unable to connect List to dropdown in angular

Having trouble connecting dropdown with a List in AngularJS: <select> <option ng-repeat="x in list">{{x}}</option> </select> app.controller('myCtrl', function($scope) { $Scope.list=[{id:1, name='name 1' ...

Strangely odd actions from a JavaScript timepiece

After answering a question, I encountered a problem with my JavaScript clock that displays the day, time, and date on three lines. To make sure these lines have the same width, I used the BigText plugin, which works well except for one issue. tday=new A ...

Retrieve the function-level variable within the while loop's else statement

Struggling with node.js, I find myself facing the challenge of accessing a variable declared at the start of a function from an else statement nested within a do while loop: function myFunction(){ var limit = 2000; var count; var total; va ...

What is the best way to programmatically insert new rows into a table

I am currently working with the foundation 5 framework (not sure if this is relevant). I need to ensure that each CELL is treated as a distinct item/value when passing information to another page, and I am unsure of how to approach this issue. It should cr ...

Editing the content of a div in real-time by dynamically updating the innerHTML

Looking for a way to dynamically change the innerHTML of a contentEditable div using pure JavaScript, without relying on the Rangy library. I want the change to occur on keyup without losing cursor position or focus. Here is an example setup: <div id=" ...

Error: Unable to access 'author' property as it is undefined

Currently, I am in the process of learning how to create my own blog by following a tutorial on Github. The tutorial can be found at https://github.com/adrianhajdin/project_graphql_blog. However, while working with [slug].js to build localhost/3000/post/re ...

Unique: "Best Practices for Setting Angular.js Controller Data Directly in the Code"

In this scenario, I need to initialize the data from an inline script, even though I know how to achieve this using a promise on an http request. Currently, the controller is already defined in the header js: var testModule = angular.module('myTestM ...

What is the function of this.handleClick that is positioned on the LEFT side of the = operator?

I'm struggling to understand the usage of this in an ES6 constructor. Initially, I grasped the following concepts (see example below): - We utilize this.height = height; to introduce a new instance variable. - Adding a new instance method with cl ...

Discovering the technique to dynamically load various content using jQuery in a div based on its

After discovering this code to extract information from the first div with an id of container (box4) and retrieve any new data from the URL, everything was functioning correctly. However, I encountered an issue when attempting to load box5 and rerun the co ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

Searching through multiple columns in datatables

I encountered an issue with searching multiple columns in my serverside datatables. Individual column searches work fine, but when trying to search on more than one column simultaneously, the filter does not function as expected. For example, searching by ...

Live Search: Find Your Answers with Ajax

I've come across this issue multiple times, but haven't found a solution that fits my specific requirements. I've encountered several URLs with links like example.com/ajax/search?query=Thing I'm currently working on a header and using ...

Exploring AngularJS: Utilizing limitTo and filter

I'm having some trouble with using angular's limitTo and filter together. I want to search for a value in the search box, then apply a limit to the number of results displayed by entering a number in the filter box and clicking apply filter. Howe ...

Examples of using React tables with Material-UI, such as the Material-UI kitchen sink demo, will showcase how to

Can someone help me figure out why the values are not visible in the react table MUI kitchen sink? When I switch to JSON, the header is visible but the data in the table disappears. Both 'data' and 'data1' have the same structure accord ...

Struggling to remove quotation marks from a string that was originally an array before being converted?

Here is the code snippet that I am struggling with: users = [{ "userid": "45", "name": "steve" }, { "userid": "32", "name": "john" }]; getuser = users.flatMap(user => user.userid === '32' ? user.name : []); result = getuser.toSt ...

Why is it that using "return false" does not stop the page from reloading when clicked?

I've attempted using this code, but it doesn't seem to prevent the page from reloading when the onclick function is triggered. What am I missing here? Could this be a problem related to browser compatibility? function track_specs() { $('b ...

Guide for redirecting puppeteers' attention to a new pop-up interface

Currently, I am utilizing Puppeteer to carry out a test on a website. Upon clicking a button, a new popup browser window emerges displaying a report. Inside this new window lies data that I wish to extract. Is there a method for Puppeteer to switch its foc ...