I was using this function to add Texture on a Cylinder.
function createElementMaterial() {
THREE.ImageUtils.crossOrigin = '';
var t = THREE.ImageUtils.loadTexture( IMG_MACHINE );
t.wrapS = THREE.RepeatWrapping;
t.wrapT = THREE.RepeatWrapping;
t.offset.x = 90/(2*Math.PI);
var m = new THREE.MeshBasicMaterial();
m.map = t;
return m;
}
which is working and adds Texture, but in console it sets a warning message.
THREE.ImageUtils.loadTexture has been deprecated. Use
THREE.TextureLoader() instead.
Then following this documentation from threejs.org. I changed the function to this.
function createElementMaterial() {
var loader = new THREE.TextureLoader();
// load a resource
loader.load(
// resource URL
IMG_MACHINE,
// Function when resource is loaded
function ( texture ) {
// do something with the texture
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.offset.x = 90/(2*Math.PI);
var material = new THREE.MeshBasicMaterial( {
map: texture
} );
},
// Function called when download progresses
function ( xhr ) {
console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
},
// Function called when download errors
function ( xhr ) {
console.log( 'An error happened' );
}
);
}
With this code I am not being able to get that texture wrapping cylinder. Here's the before and after image.
TIA.
You have to return a material from your function. You can do it like this:
function createElementMaterial() {
var material = new THREE.MeshBasicMaterial(); // create a material
var loader = new THREE.TextureLoader().load(
// resource URL
IMG_MACHINE,
// Function when resource is loaded
function ( texture ) {
// do something with the texture
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.offset.x = 90/(2*Math.PI);
material.map = texture; // set the material's map when when the texture is loaded
},
// Function called when download progresses
function ( xhr ) {
console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
},
// Function called when download errors
function ( xhr ) {
console.log( 'An error happened' );
}
);
return material; // return the material
}
Related
I am trying to use Three js to load in a 3d heart model and attach a picture to the front of the heart but it seems the heart isn’t showing up at all even without loading the image in. I am new at Three js so I might be doing it all wrong but I tried using the code straight from the documents and it still isn’t working. I am getting no errors and I can see AxesHelper also I have loaded in a cube and that works so I don't think there is a problem with my scene.
function handleHeart(img) {
document.getElementById("divRight").innerHTML = ""
let renderer = new THREE.WebGLRenderer();
document.getElementById("divRight").appendChild(renderer.domElement);
let w = document.getElementById("divRight").clientWidth
let h = 600
renderer.setSize( w, h)
let camera = new THREE.PerspectiveCamera(35, w / h, 0.1, 3000 );
const controls = new THREE.OrbitControls( camera, renderer.domElement );
camera.position.set( 0, 0, 10 );
camera.lookAt(new THREE.Vector3(0, 0, 0))
controls.update();
let scene = new THREE.Scene();
scene.background = new THREE.Color( 'grey' );
light = new THREE.AmbientLight(0xffffff);
scene.add(light);
const loader = new THREE.GLTFLoader();
loader.load(
// resource URL
'models/heart_v1.glb',
// called when the resource is loaded
function ( gltf ) {
let material = new THREE.MeshBasicMaterial( { map: img } );
let model = gltf.scene || gltf.scenes[0];
//model.scale.set(1000,1000,1000)
model.material = material
scene.add(model)
model.position.z = -10
},
// called while loading is progressing
function ( xhr ) {
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
// called when loading has errors
function ( error ) {
console.log(error)
console.log( 'An error happened' );
})
scene.add(new THREE.AxesHelper(100))
renderer.render(scene, camera)
}
here is a replit : https://repl.it/#AlecStein44/Threejs-help#javascript.js
model.material = material
This line is incorrect. It should be:
model.traverse( function( object ) {
if ( object.isMesh ) object.material = material;
} );
Notice that applying a texture will still not work since your model heart_v1.glb has no texture coordinates.
What I want
I am quite new to Three.js and I am trying to apply a texture to a loaded object.
The problem
I have tried quite a few things and still not sure how to do this. I don't get any errors and the object loads in but with no texture.
My code
var loader6 = new THREE.OBJLoader();
// load a resource
loader6.load(
// resource URL
'models/Chair.obj',
// called when resource is loaded
function ( object ) {
object.scale.x = 20;
object.scale.y = 30;
object.scale.z = 20;
object.rotation.y = -0.3;
object.position.z = -500;
object.position.x = 30;
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
console.log(texture);
child.material.map = texture;
}
});
var texture = new THREE.TextureLoader().load('models/Chair.mtl');
object6 = object;
scene.add( object6 );
},
Any help?
You can not load .mtl file using TextureLoader, you have to use MTLLoader for that. MTLLoader should load the texture. Then you have to set the material to OBJLoader using 'setMaterial' function.
Checkout this code -
new THREE.MTLLoader()
.setPath( 'path to the material folder' )
.load( 'material_file.mtl', function ( materials ) {
materials.preload();
new THREE.OBJLoader()
.setMaterials( materials )
.setPath( 'path to the obj folder' )
.load( 'objModel.obj', function ( object ) {
object.position.y = - 95;
scene.add( object );
}, onProgress, onError );
} );
I'm currently working on my little project using three.js, but I am having hard time mapping texture on objects loaded by THREE.OBJLoader. There is no such problem for three.js built in geometry. I'm really confused now...
// Load the model from obj file [teapot, 74KB]
var onProgress = function ( xhr ) {
};
var onError = function ( xhr ) {
};
//var oCubeMap = THREE.ImageUtils.loadTexture(imageNames);
var objTexture = new THREE.ImageUtils.loadTexture(textureImage);
var oMaterial = new THREE.MeshLambertMaterial( { map: objTexture } );
var ooMaterial = new THREE.MeshPhongMaterial( { color: 0x99CCFF } );
var thisTexture = THREE.ImageUtils.loadTexture( textureImage, {}, function() {
renderer.render(scene, camera);
} );
var loader = new THREE.OBJLoader();
loader.load(teapot, function (object) {
object.position.set(8, -5, -25);
object.scale.set(0.04, 0.04, 0.04);
object.rotation.set(0, 180 * Math.PI / 180, 0);
// object.color = '0x99CCFF';
object.material = ooMaterial;
// object.texture = thisTexture;
scene.add(object);
}, onProgress, onError);
As you can see I've tried several things like color, material and texture but nothing worked so far. Can anyone tell me how to apply a texture onto this object?
OBJLoader returns an object with children. Add the following to your loader callback function:
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material.map = texture;
}
} );
Make sure your model geometry has UVs, otherwise textures are not supported.
three.js r.73
I am learning threejs and I want that my cube has 6 different textures on each side. I did make that with loadTexture
var material3 = new THREE.MeshPhongMaterial( {map: THREE.ImageUtils.loadTexture('textures/ps.png')} );
I did save 6 of this materials in array and then use THREE.MeshFaceMaterial. But there is problem with THREE.ImageUtils.loadTexture because it is deprecated and I should use THREE.TextureLoader and I do not know how to load 6 textures in this way.
This is what I have:
function texture()
{
var loader = new THREE.TextureLoader();
loader.load( 'textures/ps.png', function ( texture )
{
var geometry = new THREE.CubeGeometry( 10, 10, 10 );
var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
mesh = new THREE.Mesh( geometry, material );
mesh.position.z = -50;
scene.add( mesh );
} );
}
I think this is close to what you are looking for:
function MultiLoader(TexturesToLoad, LastCall, ReturnObjects) {
if (TexturesToLoad.length == 0) return;
if (!ReturnObjects) ReturnObjects = [];
var loader = new THREE.TextureLoader()
//Pop off the latest in the ,
//you could use shift instead if you want to read the array from
var texture = TexturesToLoad.shift()
loader.load(texture,
function (texture) {
ReturnObjects.push(texture);
if (TexturesToLoad.length > 0) {
MultiLoader(TexturesToLoad, LastCall, ReturnObjects)
} else {
LastCall(ReturnObjects)
}
},
LoadProgress,
LoadError);
}
function LoadProgress(xhr) {
console.log(('Lodaing ' + xhr.loaded / xhr.total * 100) + '% loaded ');
}
function LoadError(xhr) {
console.log('An error happened ');
}
call it with this
var TexturesToLoad = []
TexturesToLoad.push("../surfacemap.jpg")
TexturesToLoad.push("../normalmap.jpg");
TexturesToLoad.push("../spekularmap.jpg");
var ReturnedMaterials=[];
var ReturnMaterials=[];
var LastCall=function(ReturnedMaterials)
{
var surfaceMap = ReturnedMaterials[0];
var normalMap = ReturnedMaterials[1];
var specularMap = ReturnedMaterials[2];
var decalMaterial = new THREE.MeshPhongMaterial(
{
map: surfaceMap,
normalMap: normalMap,
normalScale: new THREE.Vector2( 1, 1 ),
specularMap: specularMap,
transparent:false,
wireframe: false
} );
var globeGeometry = new THREE.SphereGeometry(100.0, SPHERE_SIDES, SPHERE_SIDES);
mesh = new THREE.Mesh( globeGeometry, decalMaterial );
mesh.rotation.x=Math.PI/2;
};
MultiLoader(TexturesToLoad,LastCall,ReturnMaterials)
Explanation:
The new THREE.TextureLoader, uses a callback function. This ensures that the ressource you are using is really loaded when you need to add it.
Callbacks are difficult however if you want to use a lot of material.
above MultiLoader allows you to call recursivly and then call back to the function you want to use all your materials at. The materials are collected into an array (ReturnObjects) .
There are many ways to achieve it. I'll show you 2;
1)
Make your object (cube) using own vertices and faces
.vertices.push( new THREE.Vector3( x, y, z ) );
.faces.push( new THREE.Face3( x, y, z ) );
I've prepared an example in jsfiddle.
2)
Using UV map. So first you need to prepare object with UV map in 3D software like Blender and export it as a JSON file.
I've also prepared an example in jsfiddle.
If you are not familiar with UV map or Blender, check toturials.
I've read other articles about morphing vertices, particularly my other post. Then I came up with this code, but still there are errors and I can't find the answer to my current problem.
I've read this example on https://github.com/mrdoob/three.js/blob/master/src/loaders/JSONLoader.js and used the codes there. Yet there are still problems that I can't even know what seems the problem.
Code:
<script src="js/three.min.js"></script>
<script type=text/javascript>
var camera, scene, renderer;
var geometry, material, mesh, loader;
//decalaration of javascript variables thru PHP Declaration
var customHeight = "<?php $height = ($_POST['height'])*20; print $height; ?>";
var customWidth = "<?php $width = ($_POST['width'])*20; print $width; ?>";
var init = function() {
//camera
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 10, 10000 );
camera.position.z = 1000;
//scene
scene = new THREE.Scene();
//renderer
renderer = new THREE.CanvasRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x404040 , 10);
document.body.appendChild( renderer.domElement );
customHeightWidth(customWidth, customHeight);
function customHeightWidth(width, height){
//loader
loader = new THREE.JSONLoader();
//material
material = new THREE.MeshBasicMaterial({
color: 0xffffff,
side: THREE.DoubleSide,
overdraw: false,
morphTargets: true,
wireframe: true
});
//loader function
loader = function ( showStatus ) {
THREE.Loader.call( this, showStatus );
this.withCredentials = false;
};
THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
var scope = this;
// todo: unify load API to for easier SceneLoader use
texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
this.onLoadStart();
this.loadAjaxJSON( this, url, callback, texturePath );
};
var xhr = new XMLHttpRequest();
var json = JSON.parse( xhr.responseText );
THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
var scope = this,
geometry = new THREE.Geometry(),
scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
parseMorphing( scale );
function parseMorphing( scale ) {
if ( json.morphTargets !== undefined ) {
var i, l, v, vl, dstVertices, srcVertices;
for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
geometry.morphTargets[ i ] = {};
geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
geometry.morphTargets[ i ].vertices = [];
dstVertices = geometry.morphTargets[ i ].vertices;
srcVertices = json.morphTargets [ i ].vertices;
for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
var vertex = new THREE.Vector3();
vertex.x = srcVertices[ v ] * scale;
vertex.y = srcVertices[ v + 1 ] * scale;
vertex.z = srcVertices[ v + 2 ] * scale;
dstVertices.push( vertex );
}
}
}
mesh = new THREE.Mesh(geometry, material);
scene.add( mesh );
}
};
var animate = function() {
requestAnimationFrame(animate);
//mesh.rotation.x += 0.01;
//mesh.rotation.y -= 0.05;
renderer.render(scene, camera);
}
init();
animate();
</script>
This is nothing like what you were trying to do before. Now it looks like you are trying to parse a JSON file directly, in which you should be now referencing http://threejs.org/examples/#webgl_morphtargets_horse
I see loads of problems in this script. You should refer to the source code of that link because there isn't much there and it pretty straight forward.
The block I shared with you before won't work on its own. It was simply an example of how you populate the geometry.morphTargets, you still have other things to do like setup MorphAnimation class (which the source code of the link demonstrates)