HTML & Three.js Canvas not showing up on page - javascript

I'm trying to learn how to use three.js but in my html file, the tag won't show up on my page.
Here's my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Three JS</title>
</head>
<body>
<canvas class="webgl"></canvas>
<script src="/main.js"></script>
</body>
</html>
And here's my javascript code:
import * as THREE from 'three'
const scene = new THREE.Scene()
const geometry = new THREE.SphereGeometry(3, 64, 64)
const material = new THREE.MeshStandardMaterial({
color: '#00ff83'
})
const mesh = new THREE.Mesh(geometry, material)
scene.add(mesh)
const camera = new THREE.PerspectiveCamera(45)
scene.add(camera)
const canvas = document.querySelector(".webgl")
const renderer = new THREE.WebGLRenderer({canvas})
renderer.setSize(800, 600)
renderer.render(scene, camera)
I know that the camera and object are on the same spot, but I still should be seeing a black square for my canvas. Any ideas?

Two items need to changes.
#1 source CDN is more common instead of using import
#2 camera - I don't know about PespectiveCamera but your setting is not working.
I copied from here.
HTML code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Three JS</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.148.0/three.min.js"></script>
<canvas class="webgl"></canvas>
<script src="./main.js"></script>
</body>
</html>
Script code as main.js
const scene = new THREE.Scene()
const geometry = new THREE.SphereGeometry(3, 64, 64);
const material = new THREE.MeshBasicMaterial({
color: '#00ff83'
});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); // updated
scene.add(camera)
const canvas = document.querySelector(".webgl")
const renderer = new THREE.WebGLRenderer({canvas})
renderer.setSize(800, 600)
camera.position.z = 5; // added
renderer.render(scene, camera);
Result in VS code with live server

Related

Importing threex.domevents.js

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var geometry = new THREE.BoxGeometry( 2, 0.2, 2 );
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
var cube = new THREE.Mesh( geometry, material );
var domEvents = new THREEx.DomEvents(camera, renderer.domElement)
camera.position.z = 5;
camera.position.y = 1;
body {
margin:0;
}
body {
color: rgb(47, 47, 202);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Orbit</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<script src="https://code.jquery.com/jquery-3.6.0.slim.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.101.1/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.101.1/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stats.js/7/Stats.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/16.6.0/Tween.min.js"></script>
<script src="https://unpkg.com/threex-domevents#1.0.0/threex.domevents.js"></script>
<script src="main.js"></script>
</body>
</html>
So I have hard time finding out how to import threex.domevents. Console gives me "Uncaught ReferenceError: module is not defined at threex.domevents.js:67:1" and "Uncaught ReferenceError: THREEx is not defined at main.js:1:17"
I don't want to use node.js, because I think Django is better.

How to render a three.js project?

I follow this three.js beginners tutorial and I'm stuck at part 2 because nothing is rendering on my web page. I read / watched other tutorials but I'm facing the same problem everytime.
I installed three.js with the npm install three --save command and the code is below.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First three.js Project</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<script type="module" src="./js/app.js"></script>
</body>
</html>
import * as THREE from '../node_modules/three/build/three.module.js';
import { TrackballControls } from '../node_modules/three/examples/jsm/controls/TrackballControls.js';
// Scene
const scene = new THREE.Scene();
// Camera
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.6, 1200);
camera.position.z = 5;
// Renderer
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setClearColor("#233143");
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Make Canvas Responsive
window.addEventListener('resize', () => {
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
})
// Create Box
const boxGeometry = new THREE.BoxGeometry(2, 2, 2);
const boxMaterial = new THREE.MeshLambertMaterial({ color: 0xFFFFFF });
const boxMesh = new THREE.Mesh(boxGeometry,
boxMaterial);
boxMesh.rotation.set(40, 0, 40);
scene.add(boxMesh);
const rendering = function () {
requestAnimationFrame(rendering);
// Constantly rotate box
scene.rotation.z -= 0.005;
scene.rotation.x -= 0.01;
renderer.render(scene, camera);
}
rendering();
body {
margin: 0px;
height: 100vh;
}
canvas {
display: block;
}
Something is definitely wrong, but what?
First always run three.js project in a live server not just by clicking index.html second keep file structure same as shown in image.

OBJLoader in three.js displays a black screen

I'm a complete noob in three.js and am trying to create a site that displays a .obj model, I've gone through the docs and tutorials online, I'm facing a problem where all .obj models are leading to a black screen, the code is down below along with the output.
function main(){
// creating the camera
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 0, 200);
// creating the renderer and inserting it into the html file
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// creating the scene
var scene = new THREE.Scene();
var ambientLight = new THREE.AmbientLight(0xfffff);
scene.add(ambientLight);
// loading the model along with the materials
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath( 'IronMan/' );
var url = "IronMan.mtl";
mtlLoader.load( url, function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.setPath( 'IronMan/' );
objLoader.load('IronMan.obj', function (object) {
object.position.y = - 95;
scene.add( object );
var loader = new THREE.OBJLoader();
loader.addEventListener('load', function (event){
scene.add(event.content);
});
renderer.render(scene, camera);
},
undefined,
function(err){
console.error(err);
});
});
}
main();
body{
margin: 0;
}
canvas {
position: absolute;
height: 100%;
width: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles.css">
<title>Face Model</title>
</head>
<body>
<script src='https://cdnjs.cloudflare.com/ajax/libs/three.js/108/three.min.js'></script>
<script src="https://threejs.org/examples/js/loaders/MTLLoader.js"></script>
<script src='https://cdn.jsdelivr.net/gh/mrdoob/Three.js#r92/examples/js/loaders/OBJLoader.js'></script>
<script src="app.js"></script>
</body>
</html>
Output:
Screenshot of the output
Repo link: https://github.com/chethan-hebbar/face-model

How to use THREE.MeshLine in my javascript project?

When looking for a way to create a three.js line with a changed width I came across this article which suggests to use a THREE.MeshLine class from here. However, when trying to follow the documentation on how to use it in my script I got an error:
require.js:5 Uncaught Error: Module name "three" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
at makeError (require.js:5)
at Object.o [as require] (require.js:5)
at requirejs (require.js:5)
at test_line.html:13
Here are the lines of code I used in my script:
<html>
<head>
<script src="https://requirejs.org/docs/release/2.3.5/minified/require.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r119/three.min.js"></script>
<script src="https://raw.githubusercontent.com/spite/THREE.MeshLine/master/src/THREE.MeshLine.js"></script>
<title>Test</title>
</head>
<body>
<script>
var THREE = require( 'three' );
var MeshLine = require( 'three.meshline' );
...
Do I miss something? (Hint: I am a beginner with javascript)
I also tried to follow the suggestions HERE, but as soon as I added type="module" in the script part I got an error container is not defined.
Here is a complete, stand-alone, static, easy, direct working html example of a single line in a browser window. I'd appreciate if the answer could contain a complete, stand-alone, static, easy, direct working example of the code fixed!
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r119/three.min.js"></script>
<title>Test</title>
</head>
<body>
<script>
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.set(0, 0, 150);
scene = new THREE.Scene();
scene.add(camera);
renderer = new THREE.WebGLRenderer({
clearAlpha: 1
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xcaffee, 1);
document.body.appendChild(renderer.domElement);
var material = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 10000000 } );
var points = [];
points.push( new THREE.Vector3(-50, 0, 0 ) );
points.push( new THREE.Vector3( 50, 0, 0 ) );
var geometry = new THREE.BufferGeometry().setFromPoints( points );
var line = new THREE.Line( geometry, material );
scene.add( line );
renderer.render( scene, camera );
animate();
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
</script>
</body>
</html>
Edit 2: As #user2589273 mentioned in the comment, this answer is no longer relevant, as the original repository (https://github.com/spite/THREE.MeshLine) has merged the below fork into the main repo. I will leave the answer below for posterity.
The Meshline repository you linked is not maintained any more and does not work with current three.js releases.
Here is the maintained fork that I currently use:
https://github.com/ryanking1809/threejs-meshline
It should work if you replace the link in your question with:
https://unpkg.com/threejs-meshline#2.0.11/src/index.js
Edit: with full working example:
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r119/three.min.js"></script>
<script src="https://unpkg.com/threejs-meshline#2.0.11/src/index.js"></script>
<title>Test</title>
</head>
<body>
<script>
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.set(0, 0, 150);
scene = new THREE.Scene();
scene.add(camera);
renderer = new THREE.WebGLRenderer({
clearAlpha: 1
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xcaffee, 1);
document.body.appendChild(renderer.domElement);
let points = [];
points.push( new THREE.Vector3(-50, 0, 0 ) );
points.push( new THREE.Vector3( 50, 0, 0 ) );
const line = new MeshLine();
line.setVertices(points);
const material = new MeshLineMaterial();
const mesh = new THREE.Mesh( line, material );
scene.add( mesh );
renderer.render( scene, camera );
animate();
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
</script>
</body>
</html>

Error Importing three.js through npm and browserify

i'm very new to npms and i'm trying to import three.js into my scene but it is coming up with this error despite stating the type = "module" in my script tag in my html
I installed it through an npm and here is my javascript:
var $ = require('jquery');
var three = require('three');
import * as THREE from 'three';
import OrbitControls from 'three/examples/jsm/controls/OrbitControls';
var camera, scene, renderer;
var geometry, material, mesh;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
camera.position.z = 1;
scene = new THREE.Scene();
geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
material = new THREE.MeshNormalMaterial();
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
}
function animate() {
requestAnimationFrame( animate );
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.02;
renderer.render( scene, camera );
}
Here is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="#"/>
<title>Document</title>
<script type = "module" src="/bundle.js"></script>
</head>
<body>
</body>
</html>
Sorry if the answer is obvious, using browserify and module files is very new territory for me.
Edit: So in the official documentation, it says to do this :
var THREE = require('three');
var scene = new THREE.Scene();
...
which works except I want to use
import { MapControls } from 'three/examples/jsm/controls/OrbitControls.js';
which is only available through extracting it from the orbitcontrols library. Is there a way to do this without ES6 imports and using require() instead?

Categories

Resources