ArcGIS For JavaScript结合ThreeJS功能
- 概述
- three.js中功能实现
- externalRenderers(4.28及以下版本)
- RenderNode(4.29版本)
概述
ArcGIS For Javacript提供了一些对象可以支持加载webgl上下文信息,这里包括webgl编程的代码及webgl封装的threejs的代码。并且4.29版本之前,ArcGIS For Javacript提供了externalRenderers去实现这些功能,4.29版本则摒弃了externalRenderers对象,新增了RenderNode的对象去加载第三方的渲染平台。
RenderNode相对于externalRenderers,功能上有了很大的提升。它不仅可以去加载第三方的三维渲染平台(ThreeJS)的功能,还可以对当前SceneView场景中的渲染内容进行后处理操作。
今天这里只介绍一下externalRenderers和RenderNode如何加载ThreeJS的功能操作。
three.js中功能实现
对于ThreeJS而言,一般基础的元素包含了Scene、Camera、Renderer以及三维对象。
一般步骤如下:
- 引入three.js
<script src="three.min.js">
- 创建一个场景(Scene),用于放置3D元素。
const scene = new THREE.Scene();
- 创建相机(Camera),通过相机将渲染的结果呈现给观察者。
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
- 创建渲染器(Renderer),渲染器将3D场景呈现为二维的图像,使得屏幕显示3D更真实。
//定义一个渲染器Render const renderer = new THREE.WebGLRenderer(); //设置render的渲染范围 renderer.setSize(window.innerWidth, window.innerHeight); //将场景元素添加到body中 document.body.appendChild(renderer.domElement);
- 创建3D对象,这个时候就可以创建一些球、立方体等。
//定义一个geometry,geometry定义了物体的形状,three有很多种geometry const geometry = new THREE.BoxGeometry(); const material= new THREE.MeshBasicMaterial({color: 0x00ffff}); let mesh = new THREE.Mesh(geometry, material); scene.add(mesh);
- 渲染场景,主要是将视图渲染到屏幕,这步主要为了调用我们前面创建的渲染器。
//定义渲染的动画函数 function animate() { //将animate函数添加到requestAnimationFrame,进行循环调用 requestAnimationFrame(animate); cube.rotation.x += 0.01; cube.rotation.y += 0.01; //执行渲染器的渲染函数 renderer.render(scene, camera); } //执行渲染函数 animate();
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ThreeJs基础知识_Scene</title>
<!-- <script src="./js/three.js"></script> -->
<script type="text/javascript" src="../js/threejs/r141/three.min.js"></script>
<style>
body {
margin: 0;
}
</style>
<!--
three的场景主要包括了三个对象,场景Scene,相机Camera和渲染器Render,
同时在正常应用的时候还需要包括物体 Object和控制器Contro以及灯光Light。
-->
</head>
<body>
<script>
const scene = new THREE.Scene();//创建一个场景Scene
//定义一个相机Camera( 透视摄像机 )
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
scene.rotation.x = THREE.MathUtils.degToRad(-60);
// camera.rotateZ(THREE.MathUtils.degToRad(30));
//定义一个渲染器Render
const renderer = new THREE.WebGLRenderer();
//设置render的渲染范围
renderer.setSize(window.innerWidth, window.innerHeight);
//将场景元素添加到body中
document.body.appendChild(renderer.domElement);
let geometry = new THREE.CylinderBufferGeometry(1, 0, 2, 4);
geometry.rotateX(Math.PI / 2);
geometry.computeBoundingSphere();
const material = new THREE.MeshBasicMaterial({
color: 0x00ff00,
transparent: true,
opacity: 0.5,
});//material定义了物体的材质,简单说就是外观
// 长方体作为EdgesGeometry参数创建一个新的几何体
const edges = new THREE.EdgesGeometry(geometry);
const edgesMaterial = new THREE.LineBasicMaterial({
color: 0x00ffff,
})
const line = new THREE.LineSegments(edges, edgesMaterial);
let object3D = new THREE.Object3D();
let mesh = new THREE.Mesh(geometry, material);
mesh.add(line);
object3D.add(mesh);
scene.add(object3D);//然后将物体添加到场景中去
//定义相机的z坐标,就是相机看的位置,此时要注意一下three中相机坐标系的概念,x横向,z纵向,y是竖直的,后期有兴趣可以慢慢研究three的坐标系
camera.position.z = 4;
let ambient = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambient);
//定义渲染的动画函数
function animate() {
//将animate函数添加到requestAnimationFrame,进行循环调用
requestAnimationFrame(animate);
// cube.rotation.x += 0.01;
// cube.rotation.y += 0.01;
if (object3D) {
let vec = new THREE.Vector3(0, 0, 1);
object3D.rotateOnAxis(vec, Math.PI / 300);
}
//执行渲染器的渲染函数
renderer.render(scene, camera);
}
//执行渲染函数
animate();
</script>
</body>
</html>
效果:
externalRenderers(4.28及以下版本)
externalRenderer提供了add方法,该方法支持将外部渲染器添加到当前的视图中。外部渲染器由包含一些方法和属性的对象定义的。这样就可以将其他渲染器和ArcGIS的平台融合在一起使用。
renderer的内容,可以按照ExternalRenderer的对象去定义,ExternalRenderer定义如下:
我们实例化的时候,就可以按照上面的结构去定义ExternalRenderer对象:
完成代码如下:
externalRenderClass.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ThreeJS+ArcGIS</title>
<!-- <script type="text/javascript" src="./js/threejs/r109/three.min.js"></script>
<script type="text/javascript" src="./js/threejs/r109/GLTFLoader.js"></script> -->
<script type="text/javascript" src="./js/threejs/r141/three.min.js"></script>
<script src="./externalRenderClass.js"></script>
<link rel="stylesheet" href="https://js.arcgis.com/4.28/esri/themes/light/main.css" />
<script src="https://js.arcgis.com/4.28/"></script>
<style>
html,
body,
#viewDiv {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
</style>
<script async src="https://unpkg.com/es-module-shims@1.8.0/dist/es-module-shims.js"></script>
<script>
window.THREE = THREE;
window.GLTFLoader = THREE.GLTFLoader;
require([
"esri/views/SceneView",
"esri/Map",
"esri/layers/TileLayer",
"esri/views/3d/externalRenderers"
], (SceneView, Map, TileLayer, externalRenderers) => {
// const baselayer = new TileLayer({
// url: "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer",
// });
let map = new Map({
// layers:[scenelayer]
basemap:"satellite"
})
// map.add(baselayer);
let view = new SceneView({
map: map,
container: 'viewDiv',
viewingMode: "local"
});
// let position = [13529536.50333642, 3626588.0048437016, 1000]
view.when(function () {
view.goTo({
fov: 55,
heading: 55.99495193816657,
position: {
x: 13513809.919879783,
y: 3616346.75042186,
z: 8574.5211164545,
spatialReference: {
wkid: 102100
}
},
tilt: 69.0179407311609
});
})
view.on("click",function(){
console.log(view.camera);
})
let dynamicGLTFRender = new externalRenderClass({
view,
externalRenderers
})
externalRenderers.add(view, dynamicGLTFRender);
window.view = view;
// let myExternalRenderer = {
// setup: function (context) {
// // 在外部渲染器添加到视图后执行一次。
// // 你可以使用这个函数来分配所有的静态WebGL资源(着色器,缓冲区等)。
// },
// render: function (context) {
// // 在每一帧执行,绘制几何图形到画布。在这个函数中完成的任务:
// // *更新动态资源的状态
// // *根据需要设置WebGL状态
// // *发出WebGL绘制调用
// }
// }
})
</script>
</head>
<body>
<div id="viewDiv">
</div>
</body>
</html>
index.html
class externalRenderClass {
constructor(options) {
this.opts = {
externalRenderers: null,
}
this.opts.externalRenderers = options.externalRenderers;
this.view = options.view;
this.cube = null;
this.mesh = null;
}
setParams() {
this.isStop = !this.isStop;
}
setup(context) {
let THREE = window.THREE;
// this.mixer = new THREE.AnimationMixer();
this.horseMixer = THREE.AnimationMixer;
this.clock = new THREE.Clock();
this.horseClock = new THREE.Clock();
this.mixer = THREE.AnimationMixer;
this.renderer = new THREE.WebGLRenderer({
context: context.gl, // 可用于将渲染器附加到已有的渲染环境(RenderingContext)中
premultipliedAlpha: false, // renderer是否假设颜色有 premultiplied alpha. 默认为true
});
this.renderer.setPixelRatio(window.devicePixelRatio); // 设置设备像素比。通常用于避免HiDPI设备上绘图模糊
this.renderer.setViewport(0, 0, this.view.width, this.view.height); // 视口大小设置
this.renderer.autoClear = false;
this.renderer.autoClearDepth = false;
this.renderer.autoClearColor = false;
// this.renderer.autoClearStencil = false;
let originalSetRenderTarget = this.renderer.setRenderTarget.bind(this.renderer);
this.renderer.setRenderTarget = function (target) {
originalSetRenderTarget(target);
if (target == null) {
context.bindRenderTarget();
}
};
this.scene = new THREE.Scene();
// setup the camera
let cam = context.camera;
this.camera = new THREE.PerspectiveCamera(cam.fovY, cam.aspect, cam.near, cam.far);
// 添加坐标轴辅助工具
const axesHelper = new THREE.AxesHelper(1);
axesHelper.position.copy(1000000, 100000, 100000);
this.scene.add(axesHelper);
let grid = new THREE.GridHelper(30, 10, 0xf0f0f0, 0xffffff);
this.scene.add(grid);
// setup scene lighting
this.ambient = new THREE.AmbientLight(0xffffff, 0.5);
this.scene.add(this.ambient);
let geometry = new THREE.CylinderBufferGeometry(1500, 0, 2000, 4);
geometry.rotateX(Math.PI / 2);
geometry.computeBoundingSphere();
const material = new THREE.MeshBasicMaterial({
color: 0x00ff00,
transparent: true,
opacity: 0.5,
});//material定义了物体的材质,简单说就是外观
// 长方体作为EdgesGeometry参数创建一个新的几何体
const edges = new THREE.EdgesGeometry(geometry);
const edgesMaterial = new THREE.LineBasicMaterial({
color: 0x00ffff,
})
const line = new THREE.LineSegments(edges, edgesMaterial);
let object3D = new THREE.Object3D();
let mesh = new THREE.Mesh(geometry, material);
mesh.add(line);
object3D.add(mesh);
// object3D.position.set(cenP[0], cenP[1], cenP[2] + 2000 / 2);
let position = [13529536.50333642, 3626588.0048437016, 1000];
let cenP = [];
this.opts.externalRenderers.toRenderCoordinates(this.view, [position[0], position[1], position[2]], 0, this.view.spatialReference, cenP, 0, 1);
object3D.position.set(cenP[0], cenP[1], cenP[2] + 2000 / 2);
this.scene.add(object3D);//然后将物体添加到场景中去
this.mesh = object3D;
// this.getCoords(context);
context.resetWebGLState();
}
/**
* 渲染器更新渲染
* @memberof BuildingEffect
* @method render
* @param {Object} context 已有渲染器信息,无需传值
*/
render(context) {
let THREE = window.THREE;
let cam = context.camera;
//需要调整相机的视角
this.camera.position.set(cam.eye[0], cam.eye[1], cam.eye[2]);
this.camera.up.set(cam.up[0], cam.up[1], cam.up[2]);
this.camera.lookAt(new THREE.Vector3(cam.center[0], cam.center[1], cam.center[2]));
// Projection matrix can be copied directly
this.camera.projectionMatrix.fromArray(cam.projectionMatrix);
if (this.mesh) {
let vec = new THREE.Vector3(0, 0, 1);
this.mesh.rotateOnAxis(vec, Math.PI / 300);
}
// draw the scene
/
// this.renderer.resetGLState();
this.renderer.state.reset();
//Three.js r127版本重构了WebGLState,
//this.renderer.state.reset(); 之后需要加一行 context.bindRenderTarget(); 否则渲染不出来
context.bindRenderTarget();
// this.renderer.setRenderTarget();
this.renderer.render(this.scene, this.camera);
// as we want to smoothly animate the ISS movement, immediately request a re-render
this.opts.externalRenderers.requestRender(this.view);
// cleanup
context.resetWebGLState();
}
}
效果:
RenderNode(4.29版本)
RenderNode在加载ThreeJS模块的时候和externalRenderer有些不一样。
- 调用的对象类型发生了变化。externalRenderer以class的形式调用,RenderNode必须以返回的对象类型调用。
- 内部方法名发生了变化。externalRenderer初始化的方法名为setup,RenderNode初始化的方法名为initialize。
- 调用方式不同。externalRenderer直接通过add的方式去添加并传参。RenderNode需要先通过RenderNode.createSubclass去创建子类,然后通过new一个子类对象,去传参数。
具体代码如下:
let RenderNodeClass = {
constructor(options) {
this.webgl = options.webgl;
this.view = options.view;
this.cube = null;
this.mesh = null;
this._camera = null;
},
setParams() {
this.isStop = !this.isStop;
},
initialize() {
let THREE = window.THREE;
// this.mixer = new THREE.AnimationMixer();
this.horseMixer = THREE.AnimationMixer;
this.clock = new THREE.Clock();
this.horseClock = new THREE.Clock();
this.mixer = THREE.AnimationMixer;
this.renderer = new THREE.WebGLRenderer({
context: this.gl, // 可用于将渲染器附加到已有的渲染环境(RenderingContext)中
premultipliedAlpha: false, // renderer是否假设颜色有 premultiplied alpha. 默认为true
});
this.renderer.setPixelRatio(window.devicePixelRatio); // 设置设备像素比。通常用于避免HiDPI设备上绘图模糊
this.renderer.setViewport(0, 0, this.view.width, this.view.height); // 视口大小设置
this.renderer.autoClear = false;
this.renderer.autoClearDepth = false;
this.renderer.autoClearColor = false;
// this.renderer.autoClearStencil = false;
let originalSetRenderTarget = this.renderer.setRenderTarget.bind(this.renderer);
this.renderer.setRenderTarget = function (target) {
originalSetRenderTarget(target);
if (target == null) {
context.bindRenderTarget();
}
};
this.scene = new THREE.Scene();
// setup the camera
let cam = this.camera;
this._camera = new THREE.PerspectiveCamera(cam.fovY, cam.aspect, cam.near, cam.far);
// 添加坐标轴辅助工具
const axesHelper = new THREE.AxesHelper(1);
axesHelper.position.copy(1000000, 100000, 100000);
this.scene.add(axesHelper);
let grid = new THREE.GridHelper(30, 10, 0xf0f0f0, 0xffffff);
this.scene.add(grid);
// setup scene lighting
this.ambient = new THREE.AmbientLight(0xffffff, 0.5);
this.scene.add(this.ambient);
let geometry = new THREE.CylinderBufferGeometry(1500, 0, 2000, 4);
geometry.rotateX(Math.PI / 2);
geometry.computeBoundingSphere();
const material = new THREE.MeshBasicMaterial({
color: 0x00ff00,
transparent: true,
opacity: 0.5,
});//material定义了物体的材质,简单说就是外观
// 长方体作为EdgesGeometry参数创建一个新的几何体
const edges = new THREE.EdgesGeometry(geometry);
const edgesMaterial = new THREE.LineBasicMaterial({
color: 0x00ffff,
})
const line = new THREE.LineSegments(edges, edgesMaterial);
let object3D = new THREE.Object3D();
let mesh = new THREE.Mesh(geometry, material);
mesh.add(line);
object3D.add(mesh);
// object3D.position.set(cenP[0], cenP[1], cenP[2] + 2000 / 2);
let position = [13529536.50333642, 3626588.0048437016, 1000];
let cenP = [];
this.webgl.toRenderCoordinates(this.view, [position[0], position[1], position[2]], 0, this.view.spatialReference, cenP, 0, 1);
object3D.position.set(cenP[0], cenP[1], cenP[2] + 2000 / 2);
this.scene.add(object3D);//然后将物体添加到场景中去
this.mesh = object3D;
// this.getCoords(context);
this.resetWebGLState();
},
/**
* 渲染器更新渲染
* @memberof BuildingEffect
* @method render
* @param {Object} context 已有渲染器信息,无需传值
*/
render(context) {
let THREE = window.THREE;
let cam = this.camera;
//需要调整相机的视角
this._camera.position.set(cam.eye[0], cam.eye[1], cam.eye[2]);
this._camera.up.set(cam.up[0], cam.up[1], cam.up[2]);
this._camera.lookAt(new THREE.Vector3(cam.center[0], cam.center[1], cam.center[2]));
// Projection matrix can be copied directly
this._camera.projectionMatrix.fromArray(cam.projectionMatrix);
if (this.mesh) {
let vec = new THREE.Vector3(0, 0, 1);
this.mesh.rotateOnAxis(vec, Math.PI / 300);
}
this.renderer.state.reset();
this.bindRenderTarget();
this.renderer.render(this.scene, this._camera);
// as we want to smoothly animate the ISS movement, immediately request a re-render
this.requestRender();
// cleanup
this.resetWebGLState();
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ThreeJS+ArcGIS</title>
<!-- <script type="text/javascript" src="./js/threejs/r109/three.min.js"></script>
<script type="text/javascript" src="./js/threejs/r109/GLTFLoader.js"></script> -->
<script type="text/javascript" src="./js/threejs/r141/three.min.js"></script>
<script src="./RenderNodeClass.js"></script>
<link rel="stylesheet" href="https://js.arcgis.com/4.29/esri/themes/light/main.css" />
<script src="https://js.arcgis.com/4.29/"></script>
<style>
html,
body,
#viewDiv {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
</style>
<script async src="https://unpkg.com/es-module-shims@1.8.0/dist/es-module-shims.js"></script>
<script>
window.THREE = THREE;
window.GLTFLoader = THREE.GLTFLoader;
require([
"esri/views/SceneView",
"esri/Map",
"esri/layers/TileLayer",
"esri/views/3d/webgl/RenderNode",
"esri/views/3d/webgl"
], (SceneView, Map, TileLayer, RenderNode, webgl) => {
let map = new Map({
basemap:"satellite"
})
let view = new SceneView({
map: map,
container: 'viewDiv',
viewingMode: "local"
});
view.when(function () {
view.goTo({
fov: 55,
heading: 55.99495193816657,
position: {
x: 13513809.919879783,
y: 3616346.75042186,
z: 8574.5211164545,
spatialReference: {
wkid: 102100
}
},
tilt: 69.0179407311609
});
})
view.on("click",function(){
console.log(view.camera);
})
let subRenderClass = RenderNode.createSubclass(RenderNodeClass);
view.when(function(){
new subRenderClass({
view,
webgl
})
})
// let myExternalRenderer = {
// initialize: function (context) {
// // 在外部渲染器添加到视图后执行一次。
// // 你可以使用这个函数来分配所有的静态WebGL资源(着色器,缓冲区等)。
// },
// render: function (context) {
// // 在每一帧执行,绘制几何图形到画布。在这个函数中完成的任务:
// // *更新动态资源的状态
// // *根据需要设置WebGL状态
// // *发出WebGL绘制调用
// }
// }
})
</script>
</head>
<body>
<div id="viewDiv">
</div>
</body>
</html>
结果: