Embed three.js within a div container in an HTML document

I've been attempting to place the Canvas Lines three.js inside another div, but it doesn't seem to be working as expected. Instead, when I try, the JS code places the canvas at the very end of the body. Can anyone tell me why this is happening?

My goal is to have the canvas contained within

<div id="canvas_3d"></div>
, and for the JavaScript not to append it to the end of the body.

Here is the HTML:

<section class="lc_hero hero_fulHeight" style="background-image: url('img/hero_top.jpg');">
  <div id="canvas_3d"></div>
  <div class="container">
    <div class="row">
      <%# <div class="col-md-1"></div> %>
      <div class="col-md-7">
        <div class="lc_hero__heading">
          <h1 class="head_white"><span>L</span>aboratório de <span>In</span>ovação e <span>C</span>ompetições de <span>E</span>ngenharia</h1>
          <p>Projetos que vão além da <span>faculdade!</span></p>
        </div>
      </div>
    </div>
    <div class="lc_hero__scroll_down">
      <%= svg "scroll_down" %>
    </div>
  </div>
</section>

Javascript:

var mouseX = 0,
  mouseY = 0,

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

  SEPARATION = 200,
  AMOUNTX = 10,
  AMOUNTY = 10,

  camera, scene, renderer;

init();
animate();

function init() {

  var container, separation = 100,
    amountX = 50,
    amountY = 50,
    particles, particle;

  var container = document.getElementById('canvas_3d');
  // container = document.createElement('div');
  // container.className = "canvas_3d" 
  document.body.appendChild(container);

  camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 1, 10000);
  camera.position.z = 100;

  scene = new THREE.Scene();

  renderer = new THREE.CanvasRenderer();
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  container.appendChild(renderer.domElement);

  // particles

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

    color: 0xffffff,
    program: function (context) {

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

    }

  });

  var points = [];

  for (var i = 0; i < 100; i++) {

    particle = new THREE.Sprite(material);
    particle.position.x = Math.random() * 2 - 1;
    particle.position.y = Math.random() * 2 - 1;
    particle.position.z = Math.random() * 2 - 1;
    particle.position.normalize();
    particle.position.multiplyScalar(Math.random() * 10 + 450);
    particle.scale.x = particle.scale.y = 10;
    scene.add(particle);

    points.push(particle.position);
  }

  // lines

  var geometry = new THREE.BufferGeometry().setFromPoints(points);

  var line = new THREE.Line(geometry, new THREE.LineBasicMaterial({
    color: 0xffffff,
    opacity: 0.5
  }));
  scene.add(line);

  document.addEventListener('mousemove', onDocumentMouseMove, false);
  document.addEventListener('touchstart', onDocumentTouchStart, false);
  document.addEventListener('touchmove', onDocumentTouchMove, false);

  //

  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 onDocumentMouseMove(event) {

  mouseX = event.clientX - windowHalfX;
  mouseY = event.clientY - windowHalfY;

}

function onDocumentTouchStart(event) {

  if (event.touches.length > 1) {

    event.preventDefault();

    mouseX = event.touches[0].pageX - windowHalfX;
    mouseY = event.touches[0].pageY - windowHalfY;

  }

}

function onDocumentTouchMove(event) {

  if (event.touches.length == 1) {

    event.preventDefault();

    mouseX = event.touches[0].pageX - windowHalfX;
    mouseY = event.touches[0].pageY - windowHalfY;

  }

}

//

function animate() {

  requestAnimationFrame(animate);

  render();

}

function render() {

  camera.position.x += (mouseX - camera.position.x) * .05;
  camera.position.y += (-mouseY + 200 - camera.position.y) * .05;
  camera.lookAt(scene.position);

  renderer.render(scene, camera);

}

Any help or insights would be greatly appreciated. Thank you!

Answer №1

To improve your javascript, consider eliminating the line

document.body.appendChild(container);
. This action relocates your container to the end of the body element.

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

Directive unable to recognize ng-pattern functionality

I am attempting to encapsulate an <input> within a directive in order to manage date validation, conversion from string to Date object, and keep the Date version in the original scope. The functionality seems to be working as intended. However, the n ...

No Angularjs redirection without the "onload" event

In my search for a solution, I came across this answer but it did not quite fit my needs: Pass onload event through redirect The issue I'm facing is that I want the AngularJS section of my application to reload something when the user is redirected ...

What is the recommended element for managing data in React?

Let's consider a scenario where we have 2 main components: class App extends React.Component { state = { comments: [1, 2, 3, 4] } render() { return ( <Comments /> ) } } class Comments extends React.Component { rende ...

Accessing the database variable in controller files with Node.js

I am new to node.js and currently using lowdb for my database as I start building my app. In the index.js file, I have set up my Express server along with routes: var express = require('express'); var app = express(); var bodyParser = require(& ...

Aggregating and organizing all TypeScript files within the project while preserving the file hierarchy

Looking to utilize a task runner such as Grunt or Gulp to compile TS to JS files in various locations within the project folder. The goal is to ensure that the outputted JS files are placed in the same directory where the project will look for them alongsi ...

having trouble with my lambda function reading the basic json object

I recently joined Lambda and have been attempting to create a simple JSON object. However, I keep encountering an error that says "parsing error, unexpected token." Here is my code, which I have verified to be valid JSON: { "metadata": { ...

Limiting the display of every item in Angular ngFor

I'm currently working with Angular and I have the following code in my component.html: <div class="card" *ngFor="let item of galleries;" (mouseenter)=" setBackground(item?.image?.fullpath)" (mouseover)="showCount ...

The success function in Ajax is constantly elusive, while the error function prevails. The data just can't seem to make it to the destination file

Thank you for your patience. This marks my initial post to the best of my recollection. The section below showcases a snippet from my calendar.js script. My current objective involves sending data obtained from a modal window in index.php over to sql.php. ...

Risk Score Generating Form

As I work on a comprehensive form, there are 5 sections for users to mark if they qualify (using checkmarks). The form consists of approximately 50 questions in total. Each section carries different weights/points (e.g., Section 1 is worth 1 point each, ...

Retrieve JSON data by making a POST request to a website's API

Can you help me retrieve Json data from a website API using JavaScript? I'm trying to fetch quotes from the following website: for my quotes generator page. While I have some understanding of making GET requests, it seems that this API requires POST ...

What is the best way to extract basic body content using AJAX?

How do I simply parse the string 1399508637585,2252? When I open the desired page, the response above is displayed in the browser. I also tested it with hurl.it: HEADERS Content-Length: 18 Content-Type: text/html; charset=utf-8 Date: Thu, 08 May 2014 00 ...

What is the most popular method for namespacing AngularJS modules?

I am new to AngularJS and currently exploring different ways to namespace modules in my application. One challenge I face is the need to integrate my Angular app into a designated placeholder div within a third-party website (which may also use Angular), ...

Turn off Chrome's new tab preview thumbnails

Is there a method to prevent Google Chrome from displaying certain pages as thumbnails? I am inquiring because I am developing a website that contains confidential information. As it stands now, the sensitive data can be viewed in the thumbnail preview. ...

The sendKeys() method is malfunctioning in Selenium WebDriver

When attempting to enter phone numbers into the designated field, an error is being encountered. Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element The following code snippet is involved: driver.get("https://m ...

What steps are involved in integrating OpenCV into a JavaScript project?

After recently installing OpenCV via npm using this guide: https://www.npmjs.com/package/opencv I'm facing a simple question. How can I actually utilize the OpenCV library in my project? The site provides a face detection example code snippet: cv.r ...

The delete button in the "Chip" component of React Material-UI is not functioning as expected

I'm having trouble with the "Chip" control and its "X" button functionality. Unlike the examples shown here: http://www.material-ui.com/#/components/chip Adding the "onRequestDelete" property does include the "X" button, but it doesn't respond t ...

When configuring Webpack with a rule array, JSX is not properly recognized by the tool

Here is the configuration for my webpack setup: const path = require('path'); module.exports = { entry: './src/entry.jsx', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist&ap ...

Unable to execute redirect function in Next.js 14 application

I've been working on implementing basic authentication within a Next.js app, however I'm encountering issues with redirecting to the homepage from the auth.ts file. Below is a snippet of the code where I am implementing the loginForm: //loginForm ...

Preventing users from navigating away from the page without choosing an answer in a React application

My dilemma involves the implementation of a question component, where I aim to prevent users from leaving a page without selecting an answer. Below is my question component: import React, { Component } from 'react'; import { Link } from 're ...

Tooltips experience issues when interacting with elements that do not utilize the :active state

$(function () { $('[data-toggle="tooltip"]').tooltip() }) <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" ...