Creating two separate canvas elements with their own unique JavaScript code can be achieved by first defining each

In my current project, I am utilizing the power of Three.js to craft a 3D cube that can both translate and rotate within a 3D space by harnessing data from accelerometer and gyroscope sensors.

Initially, I managed to create one canvas that accurately displays the accelerometer movements. However, now I face the challenge of setting up another separate canvas to showcase the gyroscope data independently. Ideally, I would prefer to have distinct JavaScript codes for each canvas to ensure their autonomy. Unfortunately, my attempts to create two separate canvases have been unsuccessful so far. I am uncertain if it is feasible to incorporate two different JavaScript codes within the HTML structure.

Here's an overview of how the HTML is currently structured:

HTML

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
</head>

<body>
    <canvas id="canvas" width="500" height="800" style="border:1px solid #eb1c1c;"></canvas>
    <div id="info">
        <div>t = <span id="time">0</span> s</div>
        <div>accX = <span id="accX">0</span></div>
        <div>accY = <span id="accY">0</span></div>
        <div>accZ = <span id="accZ">0</span></div>
    </div>

</body>
</html>

As seen in the provided code snippet, the JavaScript section is responsible for initializing the renderer, camera, scene, lights, objects, and handling user interactions:

[JavaScript code]

This visual representation illustrates how I envision the final canvas layout:

https://i.sstatic.net/iGO3E.png

Answer №1

If you want some good news, it is indeed possible! The key is to organize all your code, especially animations, into separate functions:

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const scene1 = new THREE.Scene();
const camera1 = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

scene.background = new THREE.Color( 0xf0000f);
scene1.background = new THREE.Color( 0x0000ff );

const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );

const renderer1 = new THREE.WebGLRenderer();
renderer1.setSize( window.innerWidth, window.innerHeight );

renderer1.domElement.width=500;
renderer1.domElement.height=300;
renderer1.domElement.style.position="absolute";
renderer1.domElement.style.top=0;
renderer1.domElement.style.height=150+"px";
renderer1.domElement.style.width=200+"px";

renderer.domElement.width=500;
renderer.domElement.height=300;
renderer.domElement.style.position="absolute";
renderer.domElement.style.top=0;


document.body.appendChild( renderer.domElement );
document.body.appendChild( renderer1.domElement );

            const geometry = new THREE.BoxGeometry();
            const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
            const cube = new THREE.Mesh( geometry, material );
            scene.add( cube );
      
      const geometry1 = new THREE.BoxGeometry(3,3,3);
            const material1 = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
            const cube1 = new THREE.Mesh( geometry1, material1 );
            scene1.add( cube1 );

            camera.position.z = 5;
      camera1.position.z = 5;

            const animate = function () {
                requestAnimationFrame( animate );

                cube.rotation.x += 0.01;
                cube.rotation.y += 0.01;

                renderer.render( scene, camera );
            };
      
      const animate1 = function () {
                requestAnimationFrame( animate1 );

                cube1.rotation.x += 0.01;
                cube1.rotation.y += 0.01;

                renderer1.render( scene1, camera1 );
            };

            animate();
      animate1();
<script src="http://threejs.org/build/three.min.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

The ng-disabled directive in Angular JS is not effectively disabling a button

Why is the button not disabled? var mainApp = angular.module('mainApp', []); mainApp.controller('mainController', function ($scope) { $scope.form = { login: '' }; }); <form ng-controller="LoginAppCtrl as ...

Set a restriction on the Bootstrap DatePicker to only show dates within a

My application features StartDate and EndDate datepickers, and I need to implement a 30-day limit on the selection range to prevent performance issues caused by loading too much data. I'm looking for a functionality where if the user picks today as t ...

Is it possible to refresh resources in Node.js without the need to restart the server?

Is there a middleware or library that allows access to files added after the server starts without requiring a restart? I currently use koa-static-folder, but it seems unable to handle this functionality. ...

Trouble with Material-UI Textfield Hinttext Functionality

When designing a textfield according to job requirements, I encountered an issue. After assigning a background color to the TextField, the hintText disappeared. To resolve this, I had to manually set the z-index of the label. Now, the hintText is visible, ...

Import components exclusively from the root/app directory in Angular 2

In my angular2 project, I used angular-cli version 1.0.0-beta.8 and angular version 2.0.0-rc.3. After running ng new or ng init, the directory structure created is as follows: create .editorconfig create README.md create src\app\app.compon ...

What is the best way to fill a JavaScript array with only the divs that are currently displaying as block elements?

In my JavaScript code, I am attempting to populate an array using jQuery. Within a <section> element, there are multiple <div> elements, but I only want to add the ones that are visible (with CSS property display: block) to the array. HTML: & ...

Is it necessary for Angular Reactive Form Validator to convert types before checking the value for min/max validation?

Preface: My motivation for asking the questions below stems from my experience with form.value.purchaseCost. When the <input> field does not have type=number, I receive a string instead of a number. This required me to manually convert it to Number ...

Achieving a cumulative running balance using Vue js for nested arrays

I am looking to calculate the running balance by subtracting AmountApplied from Amort. Here is the desired output: Line Amort Total Payment Running Balance 1 30250 10000 20250.00 30250 20250 0.00 ...

Accurate timing of brief image displays with JavaScript

I am embarking on an innovative online psychology experiment using JavaScript to explore the human ability to swiftly recognize images. This study utilizes the RSVP (Rapid Serial Visual Presentation) paradigm, a prevalent method in psychophysics that isola ...

Incorporate an external HTML page into an AngularJS application

Is there a way to seamlessly integrate an external HTML page into an AngularJS application? For example, if I have a page located at "localhost:8080/mypage/5533n", is it possible to embed it within my angular app? I am attempting to display a graph/table ...

A guide on incorporating Carousel.Item within another component

Working on a carousel using react-bootstrap and the current code is functioning as expected: function App() { return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic ...

Why is my v-model not being updated when using a radio button in Vue.js?

After reviewing the documentation, I attempted to implement the code provided. While I am able to successfully retrieve data for enquiryDesc, I am consistently getting a value of 5 for the rating field. I even experimented with changing the radio group to ...

Guide to transferring Laravel data to react.js

Is it feasible to import a variable value from PHP Laravel into my React.js frontend? How would one go about accomplishing this? Greetings from Zambia! The PHP variable in question is: {{$category->category_name}} and the corresponding div element i ...

Updating table width using AngularJS/jQuery after completion of ajax request

One of my challenges involves a table that defaults to a specific width, such as 80% of its parent div. Initially, the table remains hidden using 'ng-if' until an ajax call is completed in this manner: This is reflected in the HTML code snippet ...

What is the best way to send checkbox values to ActionResult in MVC5?

I am working on an MVC5 application and within my view, I have the following code snippet: <div class="form-group"> @Html.LabelFor(model => model.CategoryID, "Category", htmlAttributes: new { @class = "control-label col-md-3" }) <div c ...

The Bootstrap 4 navbar-toggler-icon is missing from the screen

Check out this code snippet: https://jsfiddle.net/8tpm4z00/ <div class="container"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#myNavigation" aria-controls="myNavigation" aria-expa ...

The input texts are intertwined with one another through an autocomplete function

My latest project involves two input fields, one for ID and the other for Name. When I enter an ID in the first input field and then move to the second (either by pressing tab or clicking), the second input field automatically populates with the correspond ...

Arranging an array of objects based on a specific keyword and its corresponding value

I have an array of objects that looks like this: [ { "type": "Exam", "value": 27 }, { "type": "Lesson", "value": 17 }, { "type": "Lesson", &qu ...

Combine the initial element of one array with the initial element of another array in JavaScript

Is there a more efficient way to concatenate the first item of one array with the first item of another array in JavaScript, and automate console.log for each pair? Check out the code snippet below: $("button#search").on("click", function(){ var inputVa ...

Tips on defining the specific CSS and JavaScript code to include in your Flask application

I am currently working on a web application using Flask and I need to specify which CSS and JS files should be included in the rendered HTML page based on a condition. There are times when I want to include mycss1.css and myjs1.js: <link href="/sta ...