console
const content = buildContentModels()
renderModel(content)
function make2dPointsAndLines() {
// 二维点数据
const points = [
[1, 1],
[2, 10],
[10, 10],
]
// 线数据,值为点数据的下标
const lines = [
[0, 1],
[2, 1],
]
return { points, lines }
}
function buildContentModels() {
const group = new THREE.Group()
// 二维点数据与线数据
const { points, lines } = make2dPointsAndLines()
// 画点
// 转换为三维点数据
const vertices = points.reduce((result, [x, y]) => {
result.push(x, 0, y)
return result
}, [])
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
const material = new THREE.PointsMaterial({ color: 0xff0000, size: 3 });
group.add(new THREE.Points(geometry, material));
// 画线
const lineMaterial = new THREE.LineBasicMaterial({ color: 0xff0000 });
lines.forEach(line => {
// 转换为三维线数据
const point0 = vertices.slice(line[0] * 3, line[0] * 3 + 3)
const point1 = vertices.slice(line[1] * 3, line[1] * 3 + 3)
const lineVertices = point0.concat(point1)
lineGeometry = new THREE.BufferGeometry();
lineGeometry.setAttribute('position', new THREE.Float32BufferAttribute(lineVertices, 3));
group.add(new THREE.Line(lineGeometry, lineMaterial));
})
return group
}
function renderModel(model) {
const scene = new THREE.Scene();
// 渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
scene.add(new THREE.GridHelper(100, 10, 0x00dddd, 0xffffff))
// 相机
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight,
0.1, 1000);
camera.position.set(0, 100, 75);
camera.lookAt(0, 0, 13)
// 环境光
const ambient = new THREE.AmbientLight(0xffffff, 0.6)
scene.add(ambient)
// 内容
scene.add(model)
// 动画
const animate = function () {
requestAnimationFrame(animate);
renderer.render(scene, camera);
};
animate();
}
<div>test</div>
body { margin: 0; }
canvas { width: 100%; height: 100% }