简介
我们继续上一篇 BabyLon.js 学习笔记(四) 中的内容,尝试一些添加反光和贴图材质的API。
初始场景
我们给初始场景一个点光源,用来对比之后的效果
import './style.css'
//导入babylonjs
import * as BABYLON from "babylonjs"
//创建canvas
const canvas = document.createElement("canvas");
//set canvas width and height
canvas.width = window.innerWidth;
canvas.height= window.innerHeight;
//add canvas into body
document.body.appendChild(canvas);
//create engine, true---启用抗锯齿
const engine =new BABYLON.Engine(canvas,true);
//create scene
const scene = new BABYLON.Scene(engine);
//create camera
const camera = new BABYLON.ArcRotateCamera(
"camera", //name
0, //yaw
0, //pitch
10, //radius m?
BABYLON.Vector3.Zero(), //target-- zero point of coordinate
scene //set scene where camera is put
);
//set camera position
camera.setPosition(new BABYLON.Vector3(0,5,-15));
//attatch camera to canvas , you can control it by mouse
camera.attachControl(canvas);
//add a point light
const pointlight = new BABYLON.PointLight(
"pointlight",
new BABYLON.Vector3(-1,1,0), //点光源位置
scene
);
//设置光源的颜色
pointlight.diffuse = new BABYLON.Color3(1,0.82,1.1);
//设置点光源的亮光颜色
pointlight.specular=new BABYLON.Color3(1,1,1); //1,0.87,0.1
//设置点光源强度
pointlight.intensity=0.5;
//create ground
const ground = BABYLON.MeshBuilder.CreateGround(
"ground", //name
{width: 15,
height: 15}, //地面的宽高
scene //地面网格所在的场景
);
ground.position.set(0,-2,0);
ground.receiveShadows = true;
//render scene
engine.runRenderLoop(()=>{
scene.render();
});
//listen windows size changing
window.addEventListener("resize",()=>{
engine.resize();
});
添加材质
在给地面添加反光之前需要绑定下材质
//地面材质
const groundMaterial = new BABYLON.StandardMaterial("groundMat",scene);
ground.material = groundMaterial;
- 地面高光, 就是反光部分的颜色
//地面高光
groundMaterial.specularColor = new BABYLON.Color3(0,0,1);
- 地面发光,地面材质主动发光
//地面发光
groundMaterial.emissiveColor = new BABYLON.Color3(0,1,0);
- 设置背景颜色
//设置背景
scene.clearColor=new BABYLON.Color3(1,1,1);
纹理贴图
BabyLon.js 有支持bmp,jpg,png等纹理贴图,而且贴图时候可以显示透明图层效果,这里我编辑了一个部分透明的png图片,它画布其实是个正方形,只是大部分设置为透明了。
- 设置图片读取路径
图片的路径必须放在 /public/… 路径 下才能被正常读取
- 贴图
//地面材质
const groundMaterial = new BABYLON.StandardMaterial("groundMat",scene);//创建标准材质,有很多种材质,需要自己探索
ground.material = groundMaterial;
scene.clearColor=new BABYLON.Color3(1,1,1); //背景色
groundMaterial.diffuseTexture=new BABYLON.Texture("source/hmi2.png",scene);
groundMaterial.diffuseTexture.hasAlpha=true;//启用透明,必须要写!!