three.js dev template - module
HTML
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three/build/three.webgpu.js",
"three/webgpu": "https://unpkg.com/three/build/three.webgpu.js",
"three/tsl": "https://unpkg.com/three/build/three.tsl.js",
"three/addons/": "https://unpkg.com/three/examples/jsm/"
}
}
</script>
CSS
body {
margin: 0px;
}
JavaScript
import * as THREE from "https://unpkg.com/three/build/three.module.js";
import { OrbitControls } from "https://unpkg.com/three/examples/jsm/controls/OrbitControls.js";
import { GUI } from "https://unpkg.com/three/examples/jsm/libs/lil-gui.module.min.js";
let camera, scene, renderer, controls;
const params = {
offset: new THREE.Vector2()
};
const TEXTURE_SIZE = 8
function createPatternTexture() {
const data = new Uint8Array(TEXTURE_SIZE * TEXTURE_SIZE * 4);
const colors = [
[0, 0, 0], // Black
[255, 0, 0], // Red
[0, 255, 0], // Green
[0, 0, 255], // Blue
];
for (let y = 0; y < TEXTURE_SIZE; y++) {
for (let x = 0; x < TEXTURE_SIZE; x++) {
const colorIndex = ((x % 2) + (y % 2) * 2); // Pattern repeats every 2 pixels
const color = colors[colorIndex];
const index = (y * TEXTURE_SIZE + x) * 4;
data[index] = color[0];
data[index + 1] = color[1];
data[index + 2] = color[2];
data[index + 3] = 0
}
}
const texture = new THREE.DataTexture(data, TEXTURE_SIZE, TEXTURE_SIZE);
texture.needsUpdate = true;
texture.magFilter = THREE.NearestFilter; // To keep sharp edges of the pattern
texture.minFilter = THREE.NearestFilter;
return texture;
}
const vertexShader = `
varying vec2 vUv;
void main(){
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position , 1.);
}
`
const fragmentShader = `
varying vec2 vUv;
uniform sampler2D uTexture;
uniform vec2 uOffset;
uniform float uTextureSize;
void main(){
//read the texture
//vec3 color = texture2D(uTexture,vUv).xyz;
//read the texture at some other place
vec3 color = texture2D(uTexture, vUv + uOffset/uTextureSize).xyz;
gl_FragColor = vec4(color,1.);
}
`
const material = new THREE.ShaderMaterial({
vertexShader,
fragmentShader,
uniforms:{
uOffset: { value: params.offset },
uTexture: { value: createPatternTexture(TEXTURE_SIZE)},
uTextureSize: { value: TEXTURE_SIZE}
...