3D 渲染
SpriteJS
渲染3D模型
SpriteJS
通过OGL底层,我们可以很方便地渲染出3D模型并与之交互。
const {Scene} = spritejs;
const {Mesh3d, shaders} = spritejs.ext3d;
const container = document.getElementById('container');
const scene = new Scene({
container,
displayRatio: 2,
});
const layer = scene.layer3d('fglayer', {
camera: {
fov: 35,
},
directionalLight: [0.5, 1.0, -0.3, 0.15],
});
layer.camera.attributes.pos = [8, 5, 15];
layer.camera.lookAt([0, 1.5, 0]);
const texture = layer.createTexture('https://p3.ssl.qhimg.com/t01d6c6c93fdddf1e42.jpg');
const program = layer.createProgram({
...shaders.BASE_TEXTURE,
texture,
});
const model = layer.loadModel('https://s5.ssl.qhres.com/static/1eb3e9b91a296abd.json');
const fox = new Mesh3d(program, {model});
layer.append(fox);
layer.setOrbit();
使用几何图形类
我们也可以很方便地使用几何图形类创建几何元素。
目前支持的元素有:
- Cube - 立方体
- Cylinder - 圆柱体
- Plane - 平面
- Sphere - 球体
const {Scene} = spritejs;
const {Cylinder, Sphere, Cube, shaders} = spritejs.ext3d;
const container = document.getElementById('container');
const scene = new Scene({
container,
displayRatio: 2,
});
const layer = scene.layer3d('fglayer', {
directionalLight: [1, 0, 0, 0.5],
pointLightColor: `hsl(${Math.floor(360 * Math.random())}, 50%, 50%)`,
pointLightPosition: [5, 3, 6],
camera: {
fov: 35,
},
});
layer.camera.attributes.pos = [5, 3, 6];
layer.camera.lookAt([0, 0, 0]);
const program = layer.createProgram({
...shaders.BASE_GEOMETRY,
cullFace: null,
uniforms: {
lighting: {value: [0.3, 0.8, 0.6, 0.1]},
},
});
const cylinder = new Cylinder(program);
cylinder.attributes.pos = [0, 1.3, 0];
layer.append(cylinder);
cylinder.animate([
{rotateY: 0},
{rotateY: -360},
], {
duration: 10000,
iterations: Infinity,
});
const sphere = new Sphere(program);
sphere.attr({
phiLength: Math.PI,
});
layer.append(sphere);
sphere.animate([
{rotateY: 0},
{rotateY: -360},
], {
duration: 7500,
iterations: Infinity,
});
const cube = new Cube(program);
cube.attributes.pos = [0, -1.3, 0];
layer.append(cube);
cube.animate([
{rotateY: 0},
{rotateY: -360},
], {
duration: 5000,
iterations: Infinity,
});
layer.setRaycast();
layer.addEventListener('click', (evt) => {
if(evt.target === cube) {
const colors = [];
for(let i = 0; i < 3; i++) {
const randomColor = `hsl(${Math.floor(360 * Math.random())}, 50%, 50%)`;
colors.push(randomColor, randomColor);
}
evt.target.attributes.colors = colors;
} else if(evt.target !== layer) {
evt.target.attributes.colors = `hsl(${Math.floor(360 * Math.random())}, 50%, 50%)`;
}
});
试试用鼠标点击这些几何体:
更多内容详见3D扩展