ThreeJS 服务端(node.js)渲染

爷,独闯天下 提交于 2020-01-16 07:33:17

用node.js 渲染 Three.js。

首先,安装依赖:
package.json

{
...
 "devDependencies": {
    "pngjs": "^3.4.0",
    "three": "^0.112.1",
    "three-software-renderer": "https://github.com/lanceschi/three-software-renderer.git#feature/projector-update"
  },
...
}

代码:

const THREE = require("three");
const SoftwareRenderer = require("three-software-renderer");
const PNG = require("pngjs").PNG;
const fs = require("fs");

// Build scene with cube
const width = 1024;
const height = 768;
const camera = new THREE.PerspectiveCamera(75, width / height, 1, 1000);
camera.position.z = 10;
const scene = new THREE.Scene();
var material = new THREE.MeshBasicMaterial({
  color: 0x0000ff,
});
let geometry = new THREE.BoxGeometry(2, 2, 2)
let cube = new THREE.Mesh(geometry, material);
cube.material.wireframe = true
cube.name = "cube"
scene.add(cube)

cube.rotation.x += 0.5;
cube.rotation.y += 0.6;

// Render into pixels-array (RGBA)
const renderer = new SoftwareRenderer();
renderer.setSize(width, height);
var imagedata = renderer.render(scene, camera);

// Create a PNG from the pixels array (RGBA)
const png = new PNG({
  width: width,
  height: height,
  filterType: -1
});

for (var i = 0; i < imagedata.data.length; i++) {
  png.data[i] = imagedata.data[i];
}
console.log(png.data);
if (!fs.existsSync("temp")) {
  fs.mkdirSync("temp");
}
png.pack().pipe(fs.createWriteStream("temp/example.png"));

效果:在这里插入图片描述
<全文结束>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!