JSFiddle - React, Tailwind, and code Playground
by navinleon
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/109/three.min.js"></script>
<script id="vertexShader" type="x-shader/x-vertex">
void main() {
gl_Position = projectionMatrix *
modelViewMatrix *
vec4(position,1.0);
}
</script>
<script id="fragmentShader" type="x-shader/x-fragment">
uniform sampler2D texture1;
const vec2 size = vec2(1024, 512);
void main() {
gl_FragColor = texture2D(texture1,gl_FragCoord.xy/size.xy);
}
</script>
<canvas id="c"></canvas>
CSS
body {
margin: 0;
}
#c {
width: 100vw;
height: 100vh;
display: block;
}
JavaScript
function main() {
// Uniform texture setting
const uniforms = {
texture1: { type: "t", value: new THREE.TextureLoader().load( "https://threejsfundamentals.org/threejs/resources/images/wall.jpg" ) }
};
// Material by shader
const myMaterial = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: document.getElementById('vertexShader').textContent,
fragmentShader: document.getElementById('fragmentShader').textContent
});
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({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;
var geometry=new THREE.SphereGeometry(0.4, 100, 100);
// geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
const cubes = []; // just an array we can use to rotate the cubes
const cube = new THREE.Mesh(geometry, myMaterial);
scene.add(cube);
cubes.push(cube); // add to our list of cubes to rotate
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render(time) {
time *= 0.001;
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
cubes.forEach((cube, ndx) => {
const speed = .2 + ndx * .1;
const rot = time * speed;
//cube.rotation.x = rot;
// cube.rotation.y = rot;
});
...