Having trouble getting a Three.js animation to work inside a div
? It works fine when placed directly on the body
, right? The issue seems to be related to how it is appended.
The JavaScript code has a notable difference where the container is appended:
document.body.appendChild(container);
document.getElementById('for_three').appendChild(container);
If you switch back to
document.body.appendChild(container);
and remove <div id="for_three"></div>
from the HTML file, the Three.js animation functions correctly within the body
.
Please note that due to length restrictions, I couldn't include a live preview. However, you can find the identical code in this CodePen example.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Three.js animation</title>
<style>
body { margin: 0; }
</style>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<script src="three.js"></script>
<div id="for_three"></div>
</body>
</html>
CSS:
#for_three {
position: absolute;
width: 50%;
height: 50%;
margin-top: 10%;
margin-left: 25%;
background-color: bisque;
}
JS:
// three.js - https://github.com/mrdoob/three.js
var SEPARATION = 100,
AMOUNTX = 100,
AMOUNTY = 70;
var container;
var camera, scene, renderer;
var particles, particle, count = 0;
var mouseX = 85,
mouseY = -342;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
// More JavaScript code...
function render() {
// Rendering logic here...
}