Skip to content

Instantly share code, notes, and snippets.

@niklasp
Last active July 20, 2021 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niklasp/2018938caa91ceecb6be707a517798c6 to your computer and use it in GitHub Desktop.
Save niklasp/2018938caa91ceecb6be707a517798c6 to your computer and use it in GitHub Desktop.
Beautified threejs starter with shaders
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
export default class Sketch {
constructor( options ) {
this.time = 0;
this.container = options.dom;
this.width = this.container.offsetWidth;
this.height = this.container.offsetHeight;
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera( 70, this.width / this.height, 0.01, 10 );
this.camera.position.z = 1;
this.renderer = new THREE.WebGLRenderer( { antialias: true } );
this.renderer.setSize( this.width, this.height );
this.container.appendChild( this.renderer.domElement );
this.controls = new OrbitControls( this.camera, this.renderer.domElement );
this.resize();
this.setupListeners();
this.addObjects();
this.render();
}
setupListeners() {
window.addEventListener( 'resize', this.resize.bind( this ) );
}
resize() {
this.width = this.container.offsetWidth;
this.height = this.container.offsetHeight;
this.renderer.setSize( this.width, this.height );
this.camera.aspect = this.width / this.height;
this.camera.updateProjectionMatrix();
}
addObjects() {
this.geometry = new THREE.BoxGeometry( 0.4, 0.4, 0.4 );
this.material = new THREE.MeshNormalMaterial();
this.material = new THREE.ShaderMaterial({
fragmentShader: `
void main() {
gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);
}
`,
vertexShader: `
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
`,
});
this.mesh = new THREE.Mesh( this.geometry, this.material );
this.scene.add( this.mesh );
}
render() {
this.time += 0.05;
// this.mesh.rotation.x = this.time / 2000;
// this.mesh.rotation.y = this.time / 1000;
this.renderer.render( this.scene, this.camera );
window.requestAnimationFrame( this.render.bind( this ) );
}
}
new Sketch({
dom: document.getElementById( 'container' ),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment