Published
Edited
Feb 18, 2020
1 star
Insert cell
md`# Three.js image texture`
Insert cell
renderer = {
const renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);
function render() {
requestAnimationFrame(render);
renderer.render(scene, camera)
}
render()
return renderer.domElement;
}
Insert cell
mesh = {
const cods = [[-1, 2, 0], [0, 0, 0], [1, 2, 0], [0, 1.5, 0]];
const cods1 = [[-2, 3, 0], [0, 0, 0], [2, 3, 0]];
const mesh = createMesh(cods)
const mesh1 = createMesh(cods1)
mesh.position.x = 3;
mesh1.position.x = -3;
scene.add(mesh, mesh1);
return mesh;
}
Insert cell
function createMesh(cods) {
const fitTo = 256;
let g = new THREE.Geometry();
g.vertices = cods.map(cod => new THREE.Vector3(...cod))
g.faces = (THREE.ShapeUtils.triangulateShape(g.vertices, [])).map(tri => new THREE.Face3(...tri))

g.computeBoundingBox();
const bbox = g.boundingBox;
var dX = Math.abs(bbox.max.x - bbox.min.x);
var dY = Math.abs(bbox.max.y - bbox.min.y);
const ratio = Math.max(dX, dY) / fitTo

g.faceVertexUvs = [g.faces.map(face => {
const { a, b, c } = face
const uv = [a,b,c].map(idx => {
const vertice = g.vertices[idx]
const x = vertice.x - bbox.min.x
const y = vertice.y - bbox.min.y
return new THREE.Vector2(x, y)
})

return uv
})]
console.log(g.faceVertexUvs)
const max = Math.max(dX, dY) / fitTo;
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
// texture.repeat.set(fitTo, fitTo);
texture.needsUpdate = true;
const m = new THREE.MeshBasicMaterial({ map: texture })
return new THREE.Mesh(g, m)
}
Insert cell
texture = new THREE.Texture(image);
Insert cell
scene = {
const scene = new THREE.Scene();
return scene;
}
Insert cell
camera = {
const camera = new THREE.PerspectiveCamera(45, width / height, .1, 1000);
camera.position.z = 10;
return camera
}
Insert cell
height = 500;
Insert cell
image = await FileAttachment("istockphoto-1055672174-170667a.jpg").image()
Insert cell
THREE = require('three')
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more