Skip to content

Instantly share code, notes, and snippets.

@caseyyee
Created April 13, 2017 20:23
Show Gist options
  • Save caseyyee/116c44c100a9ac7844037cfd83dd9bae to your computer and use it in GitHub Desktop.
Save caseyyee/116c44c100a9ac7844037cfd83dd9bae to your computer and use it in GitHub Desktop.
three.js Gradient texture
//three.js r.62
var mesh, renderer, scene, camera, controls;
var t = 0, ambientFactor, canvas, textureImage;
init();
animate();
function init() {
// info
info = document.createElement( 'div' );
info.style.position = 'absolute';
info.style.top = '30px';
info.style.width = '100%';
info.style.textAlign = 'center';
info.style.color = '#fff';
info.style.fontWeight = 'bold';
info.style.backgroundColor = 'transparent';
info.style.zIndex = '1';
info.style.fontFamily = 'Monospace';
info.innerHTML = 'Drag mouse to rotate camera; scroll to zoom';
document.body.appendChild( info );
renderer = new THREE.WebGLRenderer(); //Doesnt Work
// renderer = new THREE.CanvasRenderer(); //Works
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.physicallyBasedShading = true;
document.body.appendChild( renderer.domElement );
// scene
scene = new THREE.Scene();
// camera
camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.set( 20, 20, 20 );
// controls
controls = new THREE.OrbitControls( camera );
controls.minDistance = 10;
controls.maxDistance = 50;
// axes
scene.add( new THREE.AxisHelper( 20 ) );
// geometry
var geometry = new THREE.CubeGeometry( 10, 10, 10, 4, 4, 4 );
// image
var texture = new THREE.Texture( generateTexture() );
textureImage = texture.image
// material texture
var texture = new THREE.Texture( generateTexture() );
texture.needsUpdate = true; // important!
// material
var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
// mesh
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
}
function animate() {
requestAnimationFrame( animate );
controls.update();
renderer.render( scene, camera );
}
function generateTexture() {
var size = 512;
// create canvas
canvas = document.createElement( 'canvas' );
canvas.width = size;
canvas.height = size;
// get context
var context = canvas.getContext( '2d' );
// draw gradient
context.rect( 0, 0, size, size );
var gradient = context.createLinearGradient( 0, 0, size, size );
gradient.addColorStop(0, '#99ddff'); // light blue
gradient.addColorStop(1, '#ffff00'); // dark blue
context.fillStyle = gradient;
context.fill();
return canvas;
}
@mahowa
Copy link

mahowa commented Feb 5, 2021

I came across this example and thought it would be really cool to see what the result was. So I made a codesandbox see it here:
https://codesandbox.io/s/threejs-gradient-uzz2b

Note: I did have to update some of the ThreeJS code to work with the newest package

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment