p5.js |灯()函数
p5.js 中的lights()函数用于设置场景中的默认环境光和定向光。使用的默认环境光是ambientLight(128, 128, 128),定向光是directionalLight(128, 128, 128, 0, 0, -1)。此函数可用于在场景中快速添加默认灯光。
必须在代码的 draw()函数中使用lights()函数才能在场景中保持持久性。
句法:
lights()
参数:此函数不接受任何参数。
以下示例说明了 p5.js 中的lights()函数:
示例 1:
javascript
let newFont;
let lightsEnable = false;
function preload() {
newFont = loadFont('fonts/Montserrat.otf');
}
function setup() {
createCanvas(600, 300, WEBGL);
textFont(newFont, 18);
lightsEnableCheck = createCheckbox(
"Enable Default Lights", false);
lightsEnableCheck.position(20, 60);
// Toggle default light
lightsEnableCheck.changed(() => {
lightsEnable = !lightsEnable;
});
}
function draw() {
background("green");
text("Click on the checkbox to toggle the"
+ " default lights.", -285, -125);
noStroke();
shininess(15);
specularMaterial(250);
if (lightsEnable) {
// Enable the default lights
lights();
}
sphere(80);
}
javascript
let newFont;
let lightsEnable = false;
function preload() {
newFont = loadFont('fonts/Montserrat.otf');
}
function setup() {
createCanvas(600, 300, WEBGL);
textFont(newFont, 18);
lightsEnableCheck = createCheckbox(
"Enable Default Lights", false);
lightsEnableCheck.position(20, 60);
// Toggle default light
lightsEnableCheck.changed(() => {
lightsEnable = !lightsEnable;
});
}
function draw() {
background("green");
text("Click on the checkbox to toggle the"
+ " default lights.", -285, -125);
noStroke();
shininess(15);
specularMaterial(250);
if (lightsEnable) {
// Enable the default lights
lights();
}
rotateX(millis() / 1000);
rotateY(millis() / 1000);
box(100);
}
输出:
示例 2:
javascript
let newFont;
let lightsEnable = false;
function preload() {
newFont = loadFont('fonts/Montserrat.otf');
}
function setup() {
createCanvas(600, 300, WEBGL);
textFont(newFont, 18);
lightsEnableCheck = createCheckbox(
"Enable Default Lights", false);
lightsEnableCheck.position(20, 60);
// Toggle default light
lightsEnableCheck.changed(() => {
lightsEnable = !lightsEnable;
});
}
function draw() {
background("green");
text("Click on the checkbox to toggle the"
+ " default lights.", -285, -125);
noStroke();
shininess(15);
specularMaterial(250);
if (lightsEnable) {
// Enable the default lights
lights();
}
rotateX(millis() / 1000);
rotateY(millis() / 1000);
box(100);
}
输出:
在线编辑器: https://editor.p5js.org/
环境设置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
参考: https://p5js.org/reference/#/p5/lights