I render some part of my scene and I use this as a texture on my object. But now I want to export this texture as an image. Any idea on that?
This is how I create my texture object:
frameTexture = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter});
And I assign this texture on my material:
var material = new THREE.MeshBasicMaterial( {map:frameTexture.texture} );
And this is how I render it to the texture:
renderer.render(frameScene,frameCamera,frameTexture);
Now the question is how to save frameTexture as an image.
Render the image to the canvas then call toDataURL
renderer.render(sceneThatHasASingleQuadPlaneUsingFrameTexture, camera);
var dataURL = renderer.domElement.toDataURL();
You can now do things with that dataURL like open a window
window.open(dataURL, "image");
Or make an image out of it
var img = new Image();
img.src = dataURL;
document.body.appendChild(img);
Send it to some server via XHR
const xhr = new XMLHttpReqeust();
xhr.open('PUT', 'https://myserverthatsavesimages.com', true);
xhr.send(dataURL);
...
Etc...
Another easy solution is to render a scene having the texture as a background, that way you don't have to setup a camera to align it.
const texture = /** load texture with textureloader **/
const renderer = new THREE.WebGLRenderer();
renderer.setSize(400, 400);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.add(new THREE.AmbientLight("rgb(255,255,255)", 1));
// Here
scene.background = texture;
const camera = new THREE.PerspectiveCamera();
renderer.render(scene, camera);
const imageURL = renderer.domElement.toDataURL("image/png");
var anchor = document.createElement("a");
anchor.href = imageURL;
anchor.download = "preview.png";
anchor.click();
anchor.remove();
texture.dispose();
renderer.domElement.parentElement?.removeChild(renderer.domElement);
renderer.dispose();
Related
I'm newbie to both 3JS and Blender , when I export my model to .glb , then import it to my 3JS project . But somehow they are not the same.
In Blender Rendered Mode it look so smooth but in 3JS , all the color , the mesh , ... so terrible, what did i miss to adjust in 3JS project , please help me :(
(all of my Blender setting are default)
import * as THREE from 'three';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js';
import {GLTFLoader} from 'three/examples/jsm/loaders/GLTFLoader.js'
//import img
import galaxy from '../img/galaxy.jpg';
//setting value place
const monkeyURL = new URL('../asssets/racoon_2_1.glb',import.meta.url);
const renderer = new THREE.WebGLRenderer();
renderer.gammaOutput = true;
renderer.setSize(window.innerWidth,window.innerHeight); //note this place to change the size of scene to fit the html css
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth/window.innerHeight,
0.1,
1000
);
//spot light
const spotLight= new THREE.SpotLight(0xFFFFFF);
scene.add(spotLight);
spotLight.position.set(00,10,10);
spotLight.castShadow=true;
const spotLight1= new THREE.SpotLight(0xFFFFFF);
scene.add(spotLight1);
spotLight1.position.set(00,10,-10);
spotLight.castShadow=true;
spotLight.angle=0.5;
const spotLightHelper = new THREE.SpotLightHelper(spotLight);
scene.add(spotLightHelper);
//change color background or image
//renderer.setClearColor(0xFFEA00);
//const textureLoader = new THREE.TextureLoader();
//scene.background = textureLoader.load(galaxy);
//model Blender
const assetLoader = new GLTFLoader();
assetLoader.load(monkeyURL.href,function(gltf){
const model = gltf.scene;
scene.add(model);
model.position.set(0,0,0);
}, undefined, function(error){
console.error(error);
});
//orbit controls
const orbit = new OrbitControls(camera, renderer.domElement);
//axes
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
//camera
camera.position.set(0,2,5);
//functions :D
orbit.update();
function animate()
{
renderer.render(scene,camera);
}
renderer.setAnimationLoop(animate);
Get some help to fix my error
I have a GLTF version 1.0 model that I am importing into Three.js using LegacyGLTFLoader.js. When I do so, everything looks good, except that the model does not receive shadows. I am guessing that this is because the imported model's material is THREE.RawShaderMaterial, which does not support receiving shadows (I think). How can I fix this so that my imported model can receive shadows?
Here is sample code:
// Construct scene.
var scene = new THREE.Scene();
// Get window dimensions.
var width = window.innerWidth;
var height = window.innerHeight;
// Construct camera.
var camera = new THREE.PerspectiveCamera(75, width/height);
camera.position.set(20, 20, 20);
camera.lookAt(scene.position);
// Construct renderer.
var renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);
renderer.shadowMapEnabled = true;
document.body.appendChild(renderer.domElement);
// Construct cube.
var cubeGeometry = new THREE.BoxGeometry(10, 1, 10);
var cubeMaterial = new THREE.MeshPhongMaterial({color: 0x00ff00});
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube.castShadow = true;
cube.translateY(15);
scene.add(cube);
// Construct floor.
var floorGeometry = new THREE.BoxGeometry(20, 1, 20);
var floorMaterial = new THREE.MeshPhongMaterial({color: 0x00ffff});
var floor = new THREE.Mesh(floorGeometry, floorMaterial);
floor.receiveShadow = true;
scene.add(floor);
// Construct light.
var light = new THREE.DirectionalLight(0xffffff);
light.position.set(0, 20, 0);
light.castShadow = true;
scene.add(light);
// Construct light helper.
var lightHelper = new THREE.DirectionalLightHelper(light);
scene.add(lightHelper);
// Construct orbit controls.
new THREE.OrbitControls(camera, renderer.domElement);
// Construct GLTF loader.
var loader = new THREE.LegacyGLTFLoader();
// Load GLTF model.
loader.load(
"https://dl.dropboxusercontent.com/s/5piiujui3sdiaj3/1.glb",
function(event) {
var model = event.scene.children[0];
var mesh = model.children[0];
mesh.receiveShadow = true;
scene.add(model);
},
null,
function(event) {
alert("Loading model failed.");
}
);
// Animates the scene.
var animate = function () {
requestAnimationFrame(animate);
renderer.render(scene, camera);
};
// Animate the scene.
animate();
Here are my resources:
https://dl.dropboxusercontent.com/s/y2r8bsrppv0oqp4/three.js
https://dl.dropboxusercontent.com/s/5wh92lnsxz2ge1e/LegacyGLTFLoader.js
https://dl.dropboxusercontent.com/s/1jygy1eavetnp0d/OrbitControls.js
https://dl.dropboxusercontent.com/s/5piiujui3sdiaj3/1.glb
Here is a JSFiddle:
https://jsfiddle.net/rmilbert/8tqc3yx4/26/
One way to fix the problem is to replace the instance of RawShaderMaterial with MeshStandardMaterial. To get the intended effect, you have to apply the existing texture to the new material like so:
var newMaterial = new THREE.MeshStandardMaterial( { roughness: 1, metalness: 0 } );
newMaterial.map = child.material.uniforms.u_tex.value;
You also have to compute normal data for the respective geometry so lighting can be computed correctly. If you need no shadows, the unlint MeshBasicMaterial is actually the better choice.
Updated fiddle: https://jsfiddle.net/e67hbj1q/2/
Currently I'm making myself familiar with three.js and created a simple panorama viewer:
http://webentwicklung.ulrichbangert.de/threejs-image-on-sphere-inside.html
Unfortunately the vertical edges of the pillars are rippled.
When using the panorama viewer of Panorama Studio everything is fine:
http://ulrichbangert.de/heimat/Halberstadt/2018-06-10_Halberstadt_Dom_Panorama.html
var width = window.innerWidth,
height = window.innerHeight;
var scene = new THREE.Scene();
scene.add(new THREE.AmbientLight(0x333333));
var light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(5, 3, 5);
scene.add(light);
var camera = new THREE.PerspectiveCamera(45, width / height, 0.01, 1000);
camera.position.z = 1;
camera.fov = Math.max(100, Math.min(200, camera.fov));
camera.updateProjectionMatrix();
var renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);
var loader = new THREE.TextureLoader();
loader.load('images/panorama.jpg', function (texture) {
texture.anisotropy = renderer.getMaxAnisotropy();
var material = new THREE.MeshBasicMaterial({
map: texture
});
var sphere = new THREE.Mesh(
new THREE.SphereGeometry(20, 32, 32),
material
);
sphere.scale.x = -1;
sphere.rotation.x = -0.5;
scene.add(sphere);
var animate = function () {
requestAnimationFrame(animate);
sphere.rotation.y += 0.002;
renderer.render(scene, camera);
};
animate();
});
What's going wrong here?
Try adding more subdivisions to your SphereGeometry. Right now you have 32 lat & long subdivisions, which creates some unsightly straight-line deformations to your texture. If you do something like new THREE.SphereGeometry(20, 100, 100), you'll get better fidelity when texture mapping.
I have some code at https://jsfiddle.net/72mnd2yt/1/ that doesn't display the sprite I'm trying to draw. I tried to follow the code over at https://stemkoski.github.io/Three.js/Sprite-Text-Labels.html and read it line by line, but I'm not sure where I went wrong. would someone mind taking a look at it?
Here is some relevant code:
// picture
var getPicture = function(message){
var canvas = document.createElement('canvas');
canvas.width = "100%";
canvas.height = "100%";
var context = canvas.getContext('2d');
context.font = "10px";
context.fillText(message, 0, 10);
var picture = canvas.toDataURL();
// return picture;
return canvas;
};
// let there be light and so forth...
var getScene = function(){
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(
70,
$('body').width(),
$('body').height(),
1,
1000
);
var light = new THREE.PointLight(0xeeeeee);
scene.add(camera);
scene.add(light);
var renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0xefefef);
renderer.setSize($('body').width(), $('body').height());
camera.position.z = -10;
camera.lookAt(new THREE.Vector3(0, 0, 0));
return [scene, renderer, camera];
};
// now for the meat
var getLabel = function(message){
var texture = new THREE.Texture(getPicture(message));
var spriteMaterial = new THREE.SpriteMaterial(
{map: texture }
);
var sprite = new THREE.Sprite(spriteMaterial);
//sprite.scale.set(100, 50, 1.0);
return sprite
};
var setup = function(){
var scene;
var renderer;
var camera;
[scene, renderer, camera] = getScene();
$('body').append(renderer.domElement);
var label = getLabel("Hello, World!");
scene.add(label);
var animate = function(){
requestAnimationFrame(animate);
renderer.render(scene, camera);
};
animate();
};
setup();
A few points:
1) canvas.width = "100%" should be canvas.width = "100" (canvas sizes are assumed to be px). Same with canvas.height.
2) $('body').height() is 0, so the renderer canvas is not visible (you can check this out in dev tools, it's in the element tree but squashed to 0px high). I know nothing about jQuery, so not sure why this is, but I would recommend using window.innerHeight and window.innerWidth instead anyways. So renderer.setSize(window.innerWidth, window.innerHeight). You'll also want to make this change in the camera initialization.
3) Speaking of the camera initialization, you are passing in width and height as separate arguments, when there should only be an aspect ratio argument. See the docs. So
var camera = new THREE.PerspectiveCamera(70, window.innerWidth, window.innerHeight, 1, 1000)
becomes
var camera = new THREE.PerspectiveCamera(70, window.innerWidth/window.innerHeight, 1, 1000)
4) Because textures are assumed to be static, you need to add something to this part:
var texture = new THREE.Texture(getPicture(message))
texture.needsUpdate = true // this signals that the texture has changed
That's a one-time flag, so you need to set it every time the canvas changes if you want a dynamic texture. You don't have to make a new THREE.Texture each time, just add texture.needsUpdate in the render loop (or in an event that only fires when you want the texture to change, if you're going for efficiency). See the docs, under .needsUpdate.
At this point, it should work. Here are some further things to consider:
5) Instead of using Texture you could use CanvasTexture, which sets .needsUpdate for you. The fiddle you posted is using Three.js r71, which doesn't have it, but newer versions do. That would look like this:
var texture = new THREE.CanvasTexture(getPicture(message));
// no needsUpdate necessary
6) It looks like you were on this path already based on the commented out return picture, but you can use either canvas element, or a data url generated from the canvas for a texture. If getPicture now returns a data url, try this:
var texture = new THREE.TextureLoader().load(getPicture(message))
You can also indirectly use a data url with Texture:
var img = document.createElement('img')
var img = new Image()
img.src = getPicture(message)
var texture = new THREE.Texture(img);
texture.needsUpdate = true
If not, just stick with Texture or CanvasTexture, both will take a canvas element. Texture can indirectly take a url by passing in an image element whose src is set to the data url.
Fiddle with the outlined fixes:
https://jsfiddle.net/jbjw/x0uL1kbh/
I have a fairly complicated architecture where I am doing most of my stuff in Three.JS but I also have a special renderer that renders directly to a raw WebGL texture. Is it possible to use this WebGL texture in a three.js "Texture"? It looks like the Three.JS texture class is just a container for an image or video or canvas, and somewhere deep in the guts of three.js it will upload that to a real webgl texture. How can I just have Three.js render my WebGL texture onto a mesh?
#Brendan's answer no longer works.
No idea when it changed and too lazy to go look it up but as of r102
const texture = new THREE.Texture();
renderer.setTexture2D(texture, 0); // force three.js to init the texture
const texProps = renderer.properties.get(texture);
texProps.__webglTexture = glTex;
as of r103 setTexture2D no longer exists. You can use this instead
const forceTextureInitialization = function() {
const material = new THREE.MeshBasicMaterial();
const geometry = new THREE.PlaneBufferGeometry();
const scene = new THREE.Scene();
scene.add(new THREE.Mesh(geometry, material));
const camera = new THREE.Camera();
return function forceTextureInitialization(texture) {
material.map = texture;
renderer.render(scene, camera);
};
}();
const texture = new THREE.Texture();
forceTextureInitialization(texture); // force three.js to init the texture
const texProps = renderer.properties.get(texture);
texProps.__webglTexture = glTex;
'use strict';
/* global THREE */
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({
canvas: canvas
});
const fov = 75;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 5;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 2;
const scene = new THREE.Scene();
const boxWidth = 1;
const boxHeight = 1;
const boxDepth = 1;
const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
const forceTextureInitialization = function() {
const material = new THREE.MeshBasicMaterial();
const geometry = new THREE.PlaneBufferGeometry();
const scene = new THREE.Scene();
scene.add(new THREE.Mesh(geometry, material));
const camera = new THREE.Camera();
return function forceTextureInitialization(texture) {
material.map = texture;
renderer.render(scene, camera);
};
}();
const cubes = []; // just an array we can use to rotate the cubes
{
const gl = renderer.getContext();
const glTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, glTex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 2, 2, 0,
gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([
255, 0, 0, 255,
0, 255, 0, 255,
0, 0, 255, 255,
255, 255, 0, 255,
]));
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
const texture = new THREE.Texture();
forceTextureInitialization(texture);
const texProps = renderer.properties.get(texture);
texProps.__webglTexture = glTex;
const material = new THREE.MeshBasicMaterial({
map: texture,
});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
cubes.push(cube); // add to our list of cubes to rotate
}
function render(time) {
time *= 0.001;
cubes.forEach((cube, ndx) => {
const speed = .2 + ndx * .1;
const rot = time * speed;
cube.rotation.x = rot;
cube.rotation.y = rot;
});
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
<canvas id="c"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/103/three.min.js"></script>
Note: There is no such thing as "unsupported behavior" in three.js. Three.js makes no guarantee that anything you are doing today will work tomorrow. Three.js breaks whatever it wants to whenever it wants to
This is completely unsupported behaviour, but you could imitate the WebGLRenderer and set the __webglTexture property on a Texture directly. e.g.
var texure = new THREE.Texture();
var rawTexture = gl.createTexture();
texture.__webglTexture = rawTexture;
texture.__webglInit = true;
// ... use texture as a normal three.js texture ...
Again, this is completely unsupported and undefined behaviour and likely to break in future versions of three.js, but will likely work for the time being if you're after speed.
I'd instead suggest looking into WebGLRenderTarget if you can, or submitting a feature request to enable the feature correctly.