这里演示的是在html上通过引入babylon的js文件来运行代码的案例。
这是一个生成小球的例子。
babylon引用国外链接速度很慢所以我直接下载到了本地,可以去github上下载,我用的是4.1版本
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Babylonjs 基础</title>
<style>
html,
body {
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#renderCanvas {
width: 100%;
height: 100%;
touch-action: none;
}
</style>
<script src="./js/babylon.js"></script>
</head>
<body>
<canvas id="renderCanvas"></canvas>
<script>
const canvas = document.getElementById('renderCanvas');
const engine = new BABYLON.Engine(canvas, true);
engine.enableOfflineSupport = false;
/******* 创建场景 ******/
const createScene = function () {
// 实例化场景
const scene = new BABYLON.Scene(engine);
// 创建相机并添加到canvas
const camera = new BABYLON.ArcRotateCamera(
'Camera',
Math.PI / 2,
Math.PI / 2,
2,
new BABYLON.Vector3(0, 0, 5),
scene
);
camera.attachControl(canvas, true);
// 添加光
const light1 = new BABYLON.HemisphericLight('light1', new BABYLON.Vector3(1, 1, 0), scene);
const light2 = new BABYLON.PointLight('light2', new BABYLON.Vector3(0, 1, -1), scene);
// 创建内容,一个球
const sphere = BABYLON.MeshBuilder.CreateSphere('sphere', { diameter: 2 }, scene);
return scene;
};
/******* 结束创建场景 ******/
const scene = createScene();
// loop
engine.runRenderLoop(function () {
scene.render();
});
// resize
window.addEventListener('resize', function () {
engine.resize();
});
</script>
</body>
</html>
在官方的示例里你可能会看到还有另外两个引用
<script src="https://cdn.babylonjs.com/loaders/babylonjs.loaders.min.js"></script>
这一行是允许你从外部加载模型
<script src="https://code.jquery.com/pep/0.4.3/pep.js"></script>
这一行是允许你在触摸屏上运行代码
不过现在我们只要有babylon.js就可以跑了