刚刚嵌入过Three.js,我们又来镶嵌Babylon.js。话说当年玩具型的小东西,几年不看都长这么大了。还具备了编辑器,而且同时支持在线和桌面(虽然今天跑桌面遇到问题,还没解掉)。文档也很丰富。真是不能小觑了。当年的Unity3d,不也曾经是玩具吗?
在WordPress里面内嵌类似Babylon.js,或者Three.js,只要使用WordPress的Custom HTML块即可(我使用的是Block编辑方式)。比如,上面的3D场景显示的代码,就是一段用<pre></pre>包起来的自定义html代码。全部代码(在一个Custom HTML中)如下:
<pre> <canvas id="renderCanvas" width="640" height="480"></canvas> <script src="https://cdn.bootcss.com/babylonjs/4.0.3/babylon.js"></script> <script> // Get the canvas DOM element var canvas = document.getElementById('renderCanvas'); // Load the 3D engine var engine = new BABYLON.Engine(canvas, true, {preserveDrawingBuffer: true, stencil: true}); // CreateScene function that creates and return the scene var createScene = function(){ // Create a basic BJS Scene object var scene = new BABYLON.Scene(engine); // Create a FreeCamera, and set its position to {x: 0, y: 5, z: -10} var camera = new BABYLON.FreeCamera('camera1', new BABYLON.Vector3(0, 5, -10), scene); // Target the camera to scene origin camera.setTarget(BABYLON.Vector3.Zero()); // Attach the camera to the canvas camera.attachControl(canvas, false); // Create a basic light, aiming 0, 1, 0 - meaning, to the sky var light = new BABYLON.HemisphericLight('light1', new BABYLON.Vector3(0, 1, 0), scene); // Create a built-in "sphere" shape; its constructor takes 6 params: name, segment, diameter, scene, updatable, sideOrientation var sphere = BABYLON.Mesh.CreateSphere('sphere1', 16, 2, scene, false, BABYLON.Mesh.FRONTSIDE); // Move the sphere upward 1/2 of its height sphere.position.y = 1; // Create a built-in "ground" shape; its constructor takes 6 params : name, width, height, subdivision, scene, updatable var ground = BABYLON.Mesh.CreateGround('ground1', 6, 6, 2, scene, false); // Return the created scene return scene; } // call the createScene function var scene = createScene(); // run the render loop engine.runRenderLoop(function(){ scene.render(); }); // the canvas/window resize event handler window.addEventListener('resize', function(){ engine.resize(); }); </script> </pre>
注:上面的3D场景可以通过鼠标控制转动。