Setting up a div as a canvas in Three.js: Step-by-step guide

Is there a way to adjust the JavaScript in this three.js canvas example so that the scene can be contained within a specific div element on a webpage? Here is the example: https://codepen.io/PedalsUp/pen/qBqvvzR

I would like to use this as the background for a section on my website...

(Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.)

Thank you

var SEPARATION = 40, AMOUNTX = 130, AMOUNTY = 35;
var container;
var camera, scene, renderer;


if (window.WebGLRenderingContext){
renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
}
else {
renderer = new THREE.CanvasRenderer();
}


var particles, particle, count = 0;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

init();
animate();

function init() {

container = document.createElement( 'div' );
document.body.appendChild( container );
if(container) {
    container.className += container.className ? ' waves' : 'waves';
}

camera = new THREE.PerspectiveCamera( 120, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.y = 200; //changes how far back you can see i.e the particles towards horizon
camera.position.z = 350; //This is how close or far the particles are seen


camera.rotation.x = 0.45;

scene = new THREE.Scene();

particles = new Array();

var PI2 = Math.PI * 2;
var material = new THREE.SpriteCanvasMaterial( {

    color: 0x661DEE, //changes color of particles
    program: function ( context ) {

        context.beginPath();
        context.arc( 0, 0, 0.1, 0, PI2, true );
        context.fill();

    }

} );

var i = 0;

for ( var ix = 0; ix < AMOUNTX; ix ++ ) {

    for ( var iy = 0; iy < AMOUNTY; iy ++ ) {

        particle = particles[ i ++ ] = new THREE.Sprite( material );
        particle.position.x = ix * SEPARATION - ( ( AMOUNTX * SEPARATION ) / 2 );
        particle.position.z = iy * SEPARATION - ( ( AMOUNTY * SEPARATION ) - 10 );
        scene.add( particle );

    }

}

renderer = new THREE.CanvasRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( 0x090a11, 1);
container.appendChild( renderer.domElement );

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

}

function onWindowResize() {

windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;

camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();

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

}

function animate() {

requestAnimationFrame( animate );

render();

}

function render() {

var i = 0;

for ( var ix = 0; ix < AMOUNTX; ix ++ ) {

    for ( var iy = 0; iy < AMOUNTY; iy ++ ) {

        particle = particles[ i++ ];
        particle.position.y = ( Math.cos( ( ix + count ) * 0.5 ) * 20 ) + ( Math.cos( ( iy + count ) * 0.5 ) * 20 );
        particle.scale.x = particle.scale.y = ( Math.cos( ( ix + count ) * 0.3 ) + 2 ) * 4 + ( Math.cos( ( iy + count ) * 0.5 ) + 1 ) * 4;

    }

}

renderer.render( scene, camera );

// This increases or decreases speed
count += 0.1;

}

Answer №1

In the existing code, the rendering canvas is generated within the div#waves element. However, this code was written for an outdated version of three.js (r68, whereas the current version is r139). To update it, you will need to make the following changes:

renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });

Replace the above code snippet with the new renderer initialization code and delete the following:

renderer = new THREE.CanvasRenderer();

The CanvasRenderer has been removed in a previous version of three.js. Also, replace:

var material = new THREE.SpriteCanvasMaterial( ... );

With:

var material = new THREE.SpriteMaterial( ... );

For the same reason mentioned earlier.

Lastly, the line that appends the renderer to the div#waves element is:

container.appendChild( renderer.domElement );

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

Store the results in the database following the execution of a protractor test

I am completely new to angular protractor testing. I have created some test cases using the protractor framework with jasmine runner BDD style. Within a single test class, I have 10 to 12 specs, each with an expectation. Currently, I am running these tests ...

Does anyone know if it's feasible to return a value from PHP to an HTML form without relying on JavaScript?

Currently, I am in the process of learning how to create a basic web form. My goal is to develop an HTML web form that sends a number to PHP and then displays the number in another text field without refreshing the page. After doing some research online, ...

Setting up numerous instances of TinyMCE for use

I am having trouble initializing two instances of tinymce on my webpage. Even after following the guidance provided in this particular thread, I am unable to get it working. Could it be possible that I need to introduce a timeout between initializing the ...

What is the proper technique for inserting a variable into the header portion of a v-data-table from a JavaScript file?

I'm currently developing an application using Vue.js with datatables. I need to display the headers of a v-data-table component, and ideally, I would like to pass a variable that can be dynamic based on the language selected on the page. Below is the ...

What is the process of incorporating a select form within a component?

I am currently working on creating a user registration form. Once the form is filled out and the submit button is clicked, I need the values from the form to be displayed in a specific <p id="data></p> component. Can anyone assist me with this ...

Having trouble updating values in Vue3 when accessing the next item in an object?

I'm attempting to allow my users to browse through a collection of various items. Take a look at the records object below: 0: {id: 1, pipeline_id: 1, raw: '1', completion: null, processed: 0, …} 1: {id: 2, pipeline_id: 1, raw: '2&apo ...

Adjust the color of input labels using jQuery validate

I have a form where I want to change the class of the input labels when a specific field fails validation. My goal is to add the 'error' class to the spans that are directly above any invalid form elements. Here is an example of my HTML structur ...

An Alternative Approach for Executing a Function within an AngularJS Directive

I am currently working on a unique element directive that displays a user's picture and name. This directive has various configuration attributes, one of which is the uc-on-hover attribute. The purpose of this attribute is to determine what element sh ...

Display corresponding div elements upon clicking an HTML select option

Is there a way to make a div visible when a corresponding select option is clicked, while hiding others? My JavaScript skills are lacking in this area. CSS #aaa, #bbb, #ccc { display:none; } The HTML (I'm using the same id name for option and d ...

Understanding the process of globally evaluating classes from files in node.js using the Eval function

Parent script with childscript integration const fs = require('fs'); function includeFile(f) { eval.apply(global,[fs.readFileSync(f).toString()]) } includeFile(__dirname+'/fileToRead.js'); hi(); ...

Accessing JSON data in Node.js can be accomplished using various methods. By leveraging

Currently, I am attempting to retrieve data from a JSON file using nodeJS However, upon running the code, I encounter the following error message: TypeError: Cannot read property 'postcode' of undefined. Any ideas on how to resolve this issue? ...

After repeated attempts to initialize and destroy, Froala encounters issues when loading a textarea via Ajax

Whenever an EDIT button is clicked to update some Blog Data, it triggers an Ajax call that brings up a textarea for Froala and initiates the initialization process. This sequence works smoothly initially, but after a few cycles of edit/submit (1, 2, or 3 o ...

What is the best way to assign the value of a specific key in one array as the key in a different array?

I am attempting to retrieve the value feature_1 associated with the key name from the array data. I then aim to set feature_1 as the key of another array asset, with an array as its corresponding value. For example: //input: data: { name: "feature_1" ...

Using JQuery AJAX to successfully retrieve data and then smoothly applying the fadeIn

Utilizing AJAX, I am loading survey content into a container on a webpage. As part of the transition, I have implemented a fadeOut effect on the container, followed by fadeIn once the content is loaded. This method functions correctly for pages 1-4; howeve ...

When attempting to send an archiver file in NodeJS, the request may become unresponsive

In my NextJS application, I am facing the challenge of generating a large number of QR codes at once, like 300, 400, or even 500, and then packaging them into a zip file for users to download. The following code snippet demonstrates how I achieve this usin ...

When applying animations to ngIf, the elements end up overlapping

I'm struggling to animate div elements when toggled using the Angular directive *ngIf. The issue I'm facing seems to be a common delay/timing problem in animations, but I haven't been able to find a solid solution. 1) When the current elem ...

How can I use XPATH to target a div after choosing a nested element?

I had the task of creating a universal identifier to locate a dropdown menu following a label. There are 10 different forms, each with a unique structure but consistent format, which means I cannot rely on specific IDs or names. Instead, my approach was to ...

Why isn't any of my AngularJS code running as expected?

I've recently started learning AngularJS, but I'm encountering an issue where none of my code is being executed when I run the page. Instead, all I see on the website is {{angular-message}} and I'm receiving the error "Error: [ng:areq] Argum ...

Gain access to PowerBI reports effortlessly without the need to input any credentials

Seeking guidance on calling Power BI reports from an ASP.NET C# web application while passing credentials, specifically without utilizing Azure AD. Access has been granted to certain users in the Power BI Service workspace with view permissions. We aim t ...

Click to move directly to a specific section

This question may be common, but despite my research efforts, I have been unable to find a solution. I want to issue a disclaimer that I am new to javascript and jQuery. Here is an overview of what I am trying to achieve: I want two images that, when cli ...