1. 程式人生 > >Babylon.GUI官方文檔翻譯

Babylon.GUI官方文檔翻譯

allow cli ddc efi sso ber from content nco

  Babylon.GUI是一個基於Babylon.js的WebGL庫,可以用來在WebGL3D場景中生成交互性UI與動態紋理。相比於html ui,Babylon.GUI的功能較為簡化,但使用起來也更加簡單,並且具備一些適用於3D編程的獨有特性。如果你正尋找一款適用於h53d場景的ui庫,這也許正是你所需要的。

  為了減少誤解,翻譯正文使用中英文對照方式呈現,官方教程原地址:http://doc.babylonjs.com/overviews/gui

  

overviews

概述

Babylon.GUI: How to create 2D and 3D UI

如何建立2D和3D的UI

Table of contents

內容列表

  1. Introduction 簡介
  2. AdvancedDynamicTexture 高級動態紋理
  3. General properties 一般屬性
    1. Events 事件
      1. Bubbling Phase 冒泡階段
      2. Parameters 參數
    2. Alignments 分組對齊
    3. Position and size 位置和尺寸
    4. Tracking positions 追蹤位置
    5. Adaptive scaling 適應性縮放
    6. Rotation and Scaling 姿態和縮放
  4. Controls 被控對象
    1. TextBlock 文本框
      1. Resize to Fit 重新調整大小以適應內容
    2. InputText 文本輸入框
    3. Button 按鈕
      1. Visual animations 可視的動畫
      2. Custom button 自定義的按鈕
    4. Checkbox 復選框
    5. RadioButton 單選框
    6. Slider 滑塊
    7. Line 線
    8. Image 圖片
    9. VirtualKeyboard 虛擬鍵盤
      1. Keys 按鍵
      2. Layouts 布局
      3. Events 事件
  5. Containers 容器
    1. Rectangle 矩形
    2. Ellipse 橢圓
    3. StackPanel 堆棧面板
    4. ColorPicker 拾色器
  6. Helpers 幫助
  7. Focus management 焦點管理

Babylon.GUI

The Babylon.js GUI library is an extension you can use to generate interactive user interface. It is build on top of the DynamicTexture.

Babylonjs的GUI庫是一個可以用來建立交互性用戶接口的擴展。它建立在動態材質的基礎上

The latest version can be found here: https://github.com/BabylonJS/Babylon.js/tree/master/dist/preview%20release/gui.

最新的版本可以在這裏找到

And the source code is available on the main Babylon.js repo: https://github.com/BabylonJS/Babylon.js/tree/master/gui.

同時代碼可以在Babylonjs的主報告找到。

You can find a complete demo here: http://www.babylonjs.com/demos/gui/

你可以在這裏找到一個完整的示例

技術分享

Introduction

簡介

Babylon.GUI uses a DynamicTexture to generate a fully functionnal user interface.

Babylon.GUI使用一個動態紋理來建立一個具有完全功能的用戶接口。

The user interface can be full screen or projected onto any 3d object.

這個用戶接口可以是全屏的也可以在一個3D對象上編制。

AdvancedDynamicTexture

高級動態紋理

To begin with Babylon.GUI, you first need an AdvancedDynamicTexture object.

要開始使用Babylon.GUI,你首先需要一個高級動態紋理對象。

Babylon.GUI has two modes:

Babylon.GUI具有兩種模式

  • Fullscreen mode: In this mode, Babylon.GUI will cover the entire screen and will rescale to always adapt to your rendering resolution. It will also intercept clicks (including touches). To create an AdvancedDynamicTexture in fullscreen mode, just run this code:
  • 全屏模式:在這種模式下,Babylon.GUI將覆蓋整個屏幕,並且將一直根據渲染的分辨率自動縮放。它將捕獲點擊(包括觸摸)。要建立一個全屏模式的高級動態材質,只需運行以下代碼:
var advancedTexture = BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("myUI");

Here is an example of a simple fullscreen mode GUI: https://www.babylonjs-playground.com/#XCPP9Y#1 -

這裏是一個全屏模式GUI的例子

  • Texture mode: In this mode, BABYLON.GUI will be used as a texture for a given mesh. You will have to define the resolution of your texture. To create an AdvancedDynamicTexture in texture mode, just run this code:
  • 紋理模式:在這種模式下,BABYLON.GUI將作為某一個網格的紋理被使用。你必須定義你的紋理的分辨率。要建立一個紋理模式的高級動態紋理,只需運行以下代碼:
var advancedTexture2 = BABYLON.GUI.AdvancedDynamicTexture.CreateForMesh(myPlane, 1024, 1024);

Here is an example of a simple texture mode GUI: https://www.babylonjs-playground.com/#ZI9AK7#1 -

這裏是一個紋理模式GUI的例子

Please note that handling pointer move events could be costly on complex meshes, so you can turn off supporting pointer move events with a fourth parameter:

請註意在復雜的網格上處理指針移動事件對性能的消耗很大,所以你可以通過第四個參數來關閉對指針移動事件的支持:

var advancedTexture2 = BABYLON.GUI.AdvancedDynamicTexture.CreateForMesh(myPlane, 1024, 1024, false);

Once you have an AdvancedDynamicTexture object, you can start adding controls.

在你擁有一個高級動態紋理對象之後,你可以開始添加被管對象

General properties

通用的屬性

Events

事件

All controls have the following observables:

所有的被管對象都具有以下的可監聽項:

Observables

可監聽項

Comments

註釋

onPointerMoveObservable

Raised when the cursor moves over the control. Only available on fullscreen mode

當光標從被管對象上經過時觸發。只在全屏模式下有用

onPointerEnterObservable

Raised when the cursor enters the control. Only available on fullscreen mode

當光標進入被管對象時觸發。只在全屏模式下有用。

onPointerOutObservable

Raised when the cursor leaves the control. Only available on fullscreen mode

當光標離開被管對象時觸發。只在全屏模式下有用

onPointerDownObservable

Raised when pointer is down on the control.

在指針在被管對象上按下時觸發。

onPointerUpObservable

Raised when pointer is up on the control.

當指針在被管對象上擡起時觸發。

onDirtyObservable

Raised when the control is marked as dirty.

當被管對象被標記為垃圾時觸發

onAfterDrawObservable

Raised after control is drawn.

當被管對象繪制完成時觸發

You can also define that a control is invisble to events (so you can click through it for instance). To do so, just call control.isHitTestVisible.

你也可以將一個被管對象定義為對事件不可見(比如你可以讓點擊穿過它)。要做到這一點,只需使用control.isHitTestVisible屬性

Please note that onPointerMoveObservable, onPointerDownObservable and onPointerUpObservable will receive a Vector2WithInfo parameter containing the pointer coordinates (x, y) and the index of the button pressed (buttonIndex). If you want to get the pointer coordinates in local control space, you have to call control.getLocalCoordinates(coordinates).

請註意onPointerMoveObservable、onPointerDownObservable和onPointerUpObservable將獲取一個帶有信息的二元向量參數,這個參數包含光標的坐標(x,y)以及被按下的按鈕的索引(buttonIndex)。如果你想要在本地控制空間(指這個被控對象的局部坐標系,以左上角為零點)獲得光標坐標,你必須使用control.getLocalCoordinates(coordinates).

Here is an example of how to use observables: https://www.babylonjs-playground.com/#XCPP9Y#281 -

這是一個如何使用監聽器的例子:

Bubbling Phase

冒泡階段

onPointerMoveObservable, onPointerEnterObservable, onPointerDownObservable, onPointerUpObservable have a bubbling phase. When an event is notified in one of these observables inside a control, it‘ll subsequently be notified from the same observable in its parent, recursively, until there are no more parents.

onPointerMoveObservable, onPointerEnterObservable, onPointerDownObservable, onPointerUpObservable具有一個冒泡階段。當一個事件被一個被控對象內的監聽器發現時,它也將隨後被這個被控對象的父元素的監聽器發現,遞歸的向上傳播,直到沒有更多的父元素。

The EventState passed as the second argument to the callback contains the properties target and currentTarget that allow you to track the bubbling phase.

事件狀態被作為回調函數的第二個參數傳遞,它包含這個事件的所屬目標和當前目標,這允許你追蹤冒泡階段。

Parameters

參數

Property

屬性

Type

類型

Default

默認

Comments

註釋

target

any

null

The object that originally notified the event

最初發現這個事件的對象

currentTarget

any

null

The current object in the bubbling phase

冒泡階段中的當前對象

Here is an example of bubbling: http://www.babylonjs-playground.com/#7EPK2H -

這是一個冒泡的例子

Alignments

分組對齊

You can define the alignments used by your control with the following properties:

你可以使用下列的屬性定義你的被控對象使用的分組

Property

屬性

Default

默認

Comments

註釋

horizontalAlignment

BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER

Can be set to left, right or center.

可以被設為左右或中間

verticalAlignment

BABYLON.GUI.Control.VERTICAL_ALIGNMENT_CENTER

Can be set to top, bottom and center.

可以被設為頂部底部或中間

Here is an example of how to use alignments: https://www.babylonjs-playground.com/#XCPP9Y#13 -

這是一個如何使用分組對齊的例子

Position and size

位置和尺寸

You can set controls‘ position with the following properties:

你可以使用如下的屬性設置被控對象的位置:(這裏的位置設定是在分組對齊基礎上的修正位置,類似於dom中的相對定位)

Property

Type

Default

Default unit

left

ValueAndUnit

0

Pixel

top

ValueAndUnit

0

Pixel

Size can be set with:

可以這樣設置尺寸

Property

Type

Default

Default unit

width

ValueAndUnit

100%,1,“1024px”

Percentage

height

ValueAndUnit

100%

Percentage

Paddings can be set with:

可以這樣設置內邊距

Property

Type

Default

Default unit

paddingTop

ValueAndUnit

0px

Pixel

paddingBottom

ValueAndUnit

0px

Pixel

paddingLeft

ValueAndUnit

0px

Pixel

paddingRight

ValueAndUnit

0px

Pixel

Please note that paddings are inside the control. This means that the usableWidth = width - paddingLeft - paddingRight. Same for usableHeight = height - paddingTop - paddingBottom.

請註意內邊框是在被控對象內部的。這意味著可用的寬度=被控對象寬度-左側內邊距-右側內邊距。同樣的,可用高度=被控對象高度-頂部內邊距-底部內邊距

All these properties can be defined using pixel or percentage as unit. To set value as pixel, use this construct: control.left = "50px" To set value as percentage, use this construct: control.left = "50%"

所有的這些屬性可以以像素或百分比為單位進行定義。要把值設為像素數時,使用這個表達式:control.left = "50px" ,要把值設為百分比時,使用這個表達式:control.left = "50%"

You can also not define the unit (In this case the default unit will be used): control.width = 0.5 (which is equivalent to control.width = "50%").

你也可以不定義這個單位(這時使用默認的單位):control.width = 0.5(等效於control.width = "50%"

For all properties of type ValueAndUnit, you can find an associated readonly property named xxxInPixels. For instance, left works with leftInPixels which is a the left property in pixels. So if left = "50%" and the control‘s parent width is 150px then leftInPixels will be 75.

對於所有“值和單位”類型的屬性,你可以找到一個相關的只讀屬性叫做xxxInPixels。舉例來說,left屬性具有leftInPixels屬性,這個子屬性使用像素表示的left屬性的值。所以如果設置left = "50%"而被控對象的父元素的寬度是150像素則leftInPixels的值是75

Here is an example of how to use positions and sizes: https://www.babylonjs-playground.com/#XCPP9Y#14 -

這是一個如何使用位置和尺寸的例子

Tracking positions

位置追蹤

All controls can be moved to track position of a mesh. To do this, just call control.linkWithMesh(mesh). You can then offset the position with control.linkOffsetX and control.linkOffsetY.

所有的被管對象都可以移動來追蹤一個網格的位置。要做到這一點,只需要調用control.linkWithMesh(mesh).然後你可以通過control.linkOffsetXcontrol.linkOffsetY來設置被管對象與網格之間的相對位置。

Here is an example of a trackable label: https://www.babylonjs-playground.com/#XCPP9Y#16 -

這裏是一個具有追蹤能力的標簽的例子

Please note that controls that want to track position of a mesh must be at root level (at AdvancedDynamicTexture level).

請註意,追蹤網格位置的被管對象必須是在根層(直接被高級動態紋理這一層管理)的

You can also move a control to a specific coordinates in your scene with control.moveToVector3(position). Please note that the control will not stick with the vector if you change it afterwards.

你也可以將一個被管對象移動到場景中一個特定的坐標,通過control.moveToVector3(position).請註意這個被管對象將不會保持在這個三元向量的位置(而是保持在全屏ui的位置?)如果你稍後修改它的話

For Line control, you can also attach the second point to a control with line.connectedControl = control. In this case the x2 and y2 properties are used to offset the second point from the connected control.

對於線段被管對象,你還可以通過line.connectedControl = control將線段的第二個點綁定到另一個被管對象上。在這時x2和y2屬性被用來設定第二個點相對於被連接的被管對象的位置。

With these 2 options, you can create a complete trackable label: https://www.babylonjs-playground.com/#XCPP9Y#20 -

使用這兩個選項,你可以建立一個具有完全追蹤能力的標簽:

(這些標簽的一個不足是不能使用超文本標記語言來更方便的定義,而只能使用js對象方式定義)

Adaptive scaling

適應性縮放

When in fullscreen UI, you can decide to define your UI with a fixed resolution. To define this resolution, just set myAdvancedDynamicTexture.idealWidth = 600 or myAdvancedDynamicTexture.idealHeight = 400.

在全屏UI中,你可以選擇給UI定義一個固定的分辨率。要定義這個分辨率,只需設置myAdvancedDynamicTexture.idealWidth = 600 myAdvancedDynamicTexture.idealHeight = 400.

If both are set, the idealWidth will be used.

如果都設置了,將以idealWidth為主(看來改變分辨率後全屏ui仍然是鋪滿整個視口的,頂層UI的寬高比是視口的寬高比)

When ideal resolution is set, all values expressed in pixels are considered relatively to this resolution and scaled accordingly to match the current resolution.

在設置了理想分辨率之後,所有用像素表示的值都被認為是相對於這個分辨率的,並且會依此調整來適應當前的分辨率。(也就是比例不變?)

Even when ideal size is set, the fullscreen UI will be rendered at the same resolution of your canvas, but you can decide (mostly for performance reason) to force the texture to use the ideal size for resolution as well. To do so, just call myAdvancedDynamicTexture.renderAtIdealSize = true.

即使設定了理想尺寸,全屏UI仍會按照你的canvas的大小來繪制,但是你也可以決定強制紋理使用這個理想的尺寸作為分辨率(主要是為了性能)。要做到這一點,只需設置myAdvancedDynamicTexture.renderAtIdealSize = true.

Here is an example of how to use horizontal adaptive scaling: https://www.babylonjs-playground.com/#XCPP9Y#39 -

這裏是一個如何使用水平適應性縮放的例子

Rotation and Scaling

旋轉和縮放

Controls can be transformed with the following properties:

被管對象可以通過下列屬性進行變形

Property

Type

Default

Comments

rotation

number

0

Value is in radians

弧度值

scaleX

number

1

scaleY

number

1

transformCenterX

number

0.5

Define the center of transformation on X axis. Value is between 0 and 1

定義X方向變形中心的位置,取值在0到1之間。(以這個點為軸旋轉)

transformCenterY

number

0.5

Define the center of transformation on Y axis. Value is between 0 and 1

Please be aware that transformations are done at rendering level so after all computations. This means that alignment or positioning will be done first without taking transform in account.

請明確這一點,這些變形是在渲染層(APU)進行的,它們發生在這一幀所有的計算(CPU)之後。這意味著分組和定位會在不考慮變形的情況下先發生

Here is an example of how to use rotation and scaling: https://www.babylonjs-playground.com/#XCPP9Y#22 -

這裏是一個如何使用旋轉和縮放的例子

Controls

被控制對象

A control is an abstraction of a piece of UI. There are two kinds of controls:

被控制對象是UI的一片區域的抽象。有兩種被控制對象:

  • Pure controls: A pure control defines an action or an information useful for the user. It could be a TextBlock or a Button.
  • 純粹的被控制對象:純粹的被控制對象定義一個對用戶有用的行為或者信息。它可能是一個文本框或者一個按鈕。
  • Containers: Containers are used to organize your UI. They can contain other controls or containers.
  • 容器:容器被用來組織你的UI,它們可以包含其他的被控制對象或者容器。

All controls share the following properties:

所有的被控制對象具有以下的屬性

Property

Type

Default

Comments

alpha

number

1

Between 0 and 1. 0 means completely transparent. 1 means fully opaque

在0和1之間,0意為著完全的透明,1意味著完全的不透明

color

string

Black

Foreground color

前景顏色

fontFamily

string

Arial

Font family can be inherited. This means that if you set it on a container, it will be transmitted to all children of the container

字體可以是繼承的。這意味著如果你在一個容器上設置了它,它將被傳遞到這個容器的所有子元素上。

fontStyle

string

Empty string

Can be inherited. Value can be "italic", "bold" or "oblique"

字形可以被繼承。取值可以是“細斜體”、“粗體”或者“斜體”

fontSize

number

18

Can be inherited

字號可以被繼承

zIndex

number

0

the zIndex can be used to reorder controls on the z axis

可以被用來在z軸上對被管對象進行排序

Controls can be added directly to the AdvancedDynamicTexture or to a container with:

被管對象可以被直接添加給高級動態紋理或者容器,通過:

container.addControl(control);

They can be removed with:

它們可以被移除

container.removeControl(control);

You can also control the control visibility with control.isVisible = false.

你也可以控制被管對象的可見性通過control.isVisible = false.

TextBlock

文本框

The TextBlock is a simple control used to display text: https://www.babylonjs-playground.com/#XCPP9Y#2 -

文本框是一個用來顯示文字的簡單被管對象:

Here are the properties you can define:

這裏是你可以定義的屬性

Property

Type

Default

Comments

text

string

null

Text to display

要顯示的文字

textWrapping

boolean

false

Can be set to true to enable text wrapping

可以設置為true來允許換行

resizeToFit

boolean

false

Can be set to true to enable resize to fit

可以設置為true來允許根據內容改變尺寸

textHorizontalAlignment

number

BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER

Can be set to left, right or center可以設為左右或中間

textVerticalAlignment

number

BABYLON.GUI.Control.VERTICAL_ALIGNMENT_CENTER

Can be set to top, bottom or center

可以設為上下或中間

The control currently provides 1 observable:

暫時這種被管對象只提供一個專有的監聽器

Observables

Comments

onTextChangedObservable

Raised when the text has changed

在文字內容改變時觸發

Resize to Fit

適應性尺寸調整

When resizeToFit is set to true, the width and height of the rendered text will be automatically measured and applied to the TextBlock.

當適應性尺寸調整被設為true時,被渲染的文字的寬度和高度將被自動的計算,然後應用到文本框上(也就是字的大小不變,改變文本框的大小)

This property allows you to change the text and font of a TextBlock without having to worry about manually setting the estimated rendered width and height.

這個屬性允許你改變文本框的文字和字體,而不必擔心人工的設置文本框預計渲染的寬度和高度

Notice that textWrapping is ignored when resizeToFit is set to true. It doesn‘t make sense logically for both properties to be used at the same time as they contradict each other.

註意當適應性尺寸調整被設為真時,文字換行將被忽略。同時使用這兩個屬性在邏輯上沒有意義,因為它們相互矛盾。

InputText

文本輸入框

The InputText is a control used to let users insert text in a single line: https://www.babylonjs-playground.com/#UWS0TS -

文本輸入框是一個被管對象,用來支持用戶在一個單行中插入文字:

(實際測試發現這個輸入和刪除是有延遲的,並不完全可信)

Here are the properties you can define:

這裏是你可以定義的屬性

Property

Type

Default

Comments

text

string

null

Text to display

要顯示的文字

color

string

white

Foreground color

前景顏色

background

string

#222222

Background color

背景顏色

focusedBackground

string

black

Background color to use when the control is focused

在這個被管對象獲得焦點時使用的背景顏色

placeholderText

string

null

Text to display as placeholder (when there is no text defined and the control is not focused)

作為占位顯示的文本(當輸入框中沒有定義文本並且沒有獲得焦點時)

placeholderColor

string

gray

Foreground color to use when the placeholder text is displayed

在顯示占位文本時使用的前景色

autoStretchWidth

boolean

true

The control will resize horizontally to adapt to text size

被管對象將水平調整大小來適應文本尺寸

maxWidth

ValueAndUnit

100%

The maximum width allowed if autoStretchWidth is set to true

在自動調整寬度被啟用時所允許的最大寬度

margin

ValueAndUnit

10px

Margin to use on left and right inside the control itself. This margin is used to determine where the text will be drawn

在被管對象內部文字左右兩側的外邊距。這個外邊距用來決定文字繪制在哪裏。

thickness

number

1

Thickness of the border

邊框的厚度

The InputText is a focusable control. This means you can click / touch it in order to give it the focus and control over the keyboard events. You can remove the focus from the control by hitting enter or clicking outside of the control.

文本輸入框是一個可以獲取焦點的被管對象。這意味著你可以通過點擊或者觸摸把焦點賦予這個被管對象,然後可以通過鍵盤事件進行控制。你可以從被管對象移除這個焦點,通過敲擊回車或者點擊被管對象的外部。

The control provides several observables to track its state:

這種被管對象提供了一些監聽器來追蹤它的狀態:

Observables

Comments

onTextChangedObservable

Raised when the text has changed

當文字改變時觸發

onFocusObservable

Raised when the control loses the focus

失去焦點時觸發

onBlurObservable

Raised when the control gets the focus

獲得焦點時觸發

Please note that the InputText has pretty limited edition support. Here are the supported keys:

請註意這個文本輸入框只具有有限的編輯支持。這裏是它支持的按鍵:

  • Delete
  • Backspace
  • Home
  • End
  • Enter
  • Left / Right (used to move the cursor)

Furthermore, please note that due to JavaScript platform limitation, the InputText cannot invoke the onscreen keyboard. On mobile, the InputText will use the prompt() command to get user input. You can define the title of the prompt by setting control.promptMessage.

更進一步的,請註意因為JavaScript的平臺限制性,這個文本輸入框不能借助顯示在屏幕上的鍵盤(操作系統提供的虛擬鍵盤)。在移動端,這個文本輸入框將使用prompt()命令來獲取用戶的輸入。你可以定義prompt命令的標題,通過設置control.promptMessage.

Button

按鈕

A button can be used to interact with your user. Please see the events chapter to see how to connect your events with your buttons.

按鈕可以用來與你的用戶交互。請瀏覽事件的章節去了解如何將事件與你的按鈕連接

There are four kinds of buttons available out of the box:

有四種可用的按鈕

  • ImageButton: An image button is a button made with an image and a text. You can create one with:
  • 圖片按鈕:圖片按鈕是用一張圖片(圖片與按鈕的左邊對齊,然後接著是文本)和一段文本組成的按鈕。你可以用以下代碼建立它:
var button = BABYLON.GUI.Button.CreateImageButton("but", "Click Me", "textures/grass.png");

You can try it here: https://www.babylonjs-playground.com/#XCPP9Y#3 -

你可以在這裏試用它

  • ImageWithCenterTextButton: An image button made with a image background and a centered text.
  • 圖片以及居中文本按鈕:一個用圖片作為背景並且具有一段居中文本的圖片按鈕
var button = BABYLON.GUI.Button.CreateImageWithCenterTextButton("but", "Click Me", "textures/grass.png");

You can try it here: https://www.babylonjs-playground.com/#PLTRBV -

在這裏試用

  • SimpleButton: A simple button with text only
  • 簡單按鈕:簡單按鈕只有文本
var button = BABYLON.GUI.Button.CreateSimpleButton("but", "Click Me");

You can try it here: https://www.babylonjs-playground.com/#XCPP9Y#4 -

在這裏試用

  • ImageOnlyButton:
  • 只有圖片的按鈕
var button = BABYLON.GUI.Button.CreateImageOnlyButton("but", "textures/grass.png");

You can try it here: https://www.babylonjs-playground.com/#XCPP9Y#28 -

在這裏試用

Visual animations

可視動畫

By default a button will change its opacity on pointerover and will change it scale when clicked. You can define your own animations with the following callbacks:

默認情況下一個按鈕將在指針經過時改變不透明度,並且將在被點擊時改變縮放。你可以使用以下的回調函數來定義你自己的動畫效果

  • pointerEnterAnimation
  • pointerOutAnimation
  • pointerDownAnimation
  • pointerUpAnimation

Custom button

用戶自定義按鈕

You can also create a complete custom button by manually adding children to the button. Here is how the ImageButton is built:

你也可以通過手動的為按鈕添加子元素來建立一個完全自定義的按鈕。以下是如何構建圖片按鈕:

var result = new Button(name);
 
// Adding text
var textBlock = new BABYLON.GUI.TextBlock(name + "_button", text);
textBlock.textWrapping = true;
textBlock.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER;
textBlock.paddingLeft = "20%";
result.addControl(textBlock);   
 
// Adding image
var iconImage = new BABYLON.GUI.Image(name + "_icon", imageUrl);
iconImage.width = "20%";
iconImage.stretch = BABYLON.GUI.Image.STRETCH_UNIFORM;
iconImage.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
result.addControl(iconImage);            
 
return result;


Checkbox

復選框

The checkbox is used to control a boolean value. You can specify the value with checkbox.isChecked.

復選框用來控制一個布爾值。你可以通過checkbox.isChecked來設定這個值。

Changing the isChecked property will raise an observable called checkbox.onIsCheckedChangedObservable.

改變是否被選中屬性將觸發一個叫做checkbox.onIsCheckedChangedObservable的監聽。

The control is rendered using the following properties:

這個被管對象使用如下的屬性渲染:

Property

Type

Default

Comments

color

string

white

Foreground color

前景顏色

background

string

black

Background color

背景顏色

checkSizeRatio

number

0.8

Define the ratio used to compute the size of the inner checkbox (0.8 by default, which means the inner check size is equal to 80% of the control itself)

定義用來計算復選框內部尺寸的比率(默認是0.8,這意味著內部的區域占被管對象尺寸的80%)

Here is an example of a checkbox: https://www.babylonjs-playground.com/#U9AC0N#2 -

這裏是一個復選框的例子

RadioButton

單選按鈕

The radio button is used to define a value among a list by using a group of radio buttons where only one can be true. You can specify the selected value with radiobutton.isChecked.

單選按鈕通過一組只能有一個為真的單選按鈕來在一個列表中選取一個值。你可以通過radiobutton.isChecked來指定選中的值。

Changing the isChecked property will raise an observable called checkbox.onIsCheckedChangedObservable. Furthermore, if you select a radio button, all other radio buttons within the same group will turn to false.

修改是否選定屬性將觸發一個叫做checkbox.onIsCheckedChangedObservable的事件。更進一步的,如果你選中了一個單選按鈕,所有在同一個組裏的單選按鈕將轉變為假

The control is rendered using the following properties:

這個被管對象使用下列的屬性渲染:

Property

Type

Default

Comments

color

string

white

Foreground color

background

string

black

Background color

checkSizeRatio

number

0.8

Define the ratio used to compute the size of the inner checkbox (0.8 by default, which means the inner check size is equal to 80% of the control itself)

group

string

empty string

Use the group property to gather radio buttons working on the same value set

使用分組屬性來收集為同一個值工作的單選按鈕

Here is an example of a radiobutton: https://www.babylonjs-playground.com/#U9AC0N#13 -

這裏是一個單選按鈕的例子:

Slider

滑塊

The slider is used to control a value within a range. You can specify the range with slider.minimum and slider.maximum.

滑塊用來在一個範圍內控制一個值。你可以使用slider.minimumslider.maximum來指定這個範圍

The value itself is specified with slider.value and will raise an observable everytime it is changed (slider.onValueChangedObservable).

這個值本身使用slider.value指定,並且將在它每次改變時觸發一個事件(slider.onValueChangedObservable

The control is rendered using the following properties:

這個被控對象使用下列屬性渲染:

Property

Type

Default

Comments

borderColor

string

white

Color used to render the border of the thumb

用來渲染小滑塊的邊緣的顏色

color

string

white

Foreground color

前景色

background

string

black

Background color

背景色

barOffset

ValueAndUnit

5px

Offset used vertically to draw the background bar

繪制背景條的垂直偏移

thumbWidth

ValueAndUnit

30px

Width of the thumb

小滑塊的寬度

Here is an example of a slider: https://www.babylonjs-playground.com/#U9AC0N#1 -

這裏是一個滑塊的例子:

Line

線段

The line will draw a line (!!) between two points.

線段被管對象將在兩個點之間畫一條線。

Here are the properties you can define:

這裏是你可以定義的屬性:

Property

Type

Default

Comments

x1

number

0

X coordinate of the first point

第一個點的X坐標

y1

number

0

Y coordinate of the first point

x2

number

0

X coordinate of the second point

y2

number

0

Y coordinate of the second point

dash

array of numbers

Empty array

Defines the size of the dashes

定義虛線的尺寸

lineWidth

number

1

Width in pixel

以像素表示的寬度

Here is an example of a line: https://www.babylonjs-playground.com/#XCPP9Y#6 -

這是一個線段的例子

Image

圖片

Use the image control to display an image in your UI. You can control the stretch used by the image with image.stretch property. You can set it to one of these values:

使用圖像被控對象在你的UI裏顯示一張圖片。你可以使用image.stretch屬性控制這個圖片使用的拉伸方式。你可以把它設置為這些值中的一個

  • BABYLON.GUI.Image.STRETCH_NONE: Use original size
  • 使用原始尺寸
  • BABYLON.GUI.Image.STRETCH_FILL: Scale the image to fill the container (This is the default value)
  • 縮放圖片來填滿容器(默認值)
  • BABYLON.GUI.Image.STRETCH_UNIFORM: Scale the image to fill the container but maintain aspect ratio
  • 縮放圖片填滿容器,但是保持寬高比
  • BABYLON.GUI.Image.STRETCH_EXTEND: Scale the container to adapt to the image size.
  • 縮放容器來適應圖片的尺寸。

You may want to have the Image control adapt its size to the source image. To do so just call image.autoScale = true.

你可能希望讓圖片被管對象按照源圖片調整尺寸。要做到這一點只需調用image.autoScale = true.

You can change image source at any time with image.source="myimage.jpg".

你可以隨時修改圖片源通過image.source="myimage.jpg".

You can also define which part of the source image you want to use with the following properties:

你也可以使用以下屬性定義你要使用源圖片的哪個部分:

  • sourceLeft: x coordinate in the source image (in pixel)
  • 在源圖片中的x坐標(以像素表示)
  • sourceTop: y coordinate in the source image (in pixel)
  • sourceWidth: width of the source image you want to use (in pixel)
  • 你希望使用的部分的寬度
  • sourceHeight: height of the source image you want to use (in pixel)

Here is an example of an image: https://www.babylonjs-playground.com/#XCPP9Y#7 -

這是一個使用圖片的例子

VirtualKeyboard

虛擬鍵盤

The VirtualKeyboard is a control used to display simple onscreen keyboard. This is mostly useful with WebVR scenarios where the user cannot easily use his keyboard.

虛擬鍵盤是一個用來在屏幕上顯示簡單鍵盤的被管對象。它通常被使用在WebVR場景中,因為那時用戶往往不能方便的使用他的鍵盤

Keys

按鍵

You can define the keys provided by the keyboard with the following code:

你可以通過如下的代碼定義從鍵盤提供的按鍵

var keyboard = new BABYLON.GUI.VirtualKeyboard();
keyboard.addKeysRow(["1", "2", "3", "4", "5", "6", "7", "8", "9", "0","\u2190"]);

Every key will be created using default values specified by the following properties:

所有的按鍵將使用默認值建立,可以通過以下屬性設定默認值:

Property

Default

defaultButtonWidth

默認按鈕寬度

40px

defaultButtonHeight

默認按鈕高度

40px

defaultButtonPaddingLeft

默認按鈕左內邊距

2px

defaultButtonPaddingRight

默認按鈕右內邊距

2px

defaultButtonPaddingTop

上內邊距

2px

defaultButtonPaddingBottom

下內邊距

2px

defaultButtonColor

顏色(前景?)

#DDD

defaultButtonBackground

背景

#070707

You can also override each property by providing an array containing properties for keys (or null):

你也可以通過提供一個包含按鍵屬性的數組來覆蓋每一個屬性

addKeysRow(["a", "b"], [null, { width: "200px"}]);

You can define each default properties based on the following class:

你可以基於以下的類來定義每個默認屬性:

class KeyPropertySet {
      width?: string;
      height?: string;
      paddingLeft?: string;
      paddingRight?: string;
      paddingTop?: string;
      paddingBottom?: string;
      color?: string;
      background?: string;
  }

Layouts

布局

The VirtualKeyboard provides a static method to create a default layout:

虛擬鍵盤提供一個靜態方法來建立默認的布局

var keyboard = BABYLON.GUI.VirtualKeyboard.CreateDefaultLayout();

The default layout is equivalent to:

默認的布局是這樣的:

addKeysRow(["1", "2", "3", "4", "5", "6", "7", "8", "9", "0","\u2190"]);
addKeysRow(["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"]);
addKeysRow(["a", "s", "d", "f", "g", "h", "j", "k", "l",";","‘","\u21B5"]);
addKeysRow(["z", "x", "c", "v", "b", "n", "m", ",", ".", "/"]);
addKeysRow([" "], [{ width: "200px"}]);

Events

事件

Every time a key is pressed the onKeyPressObservable observable is triggered. But you can also rely on keyboard.connect(inputText) to automatically connect a VirtualKeyboard to an InputText. In this case, the keyboard will only appear when the InputText will be focused and all key pressed events will be sent to the InputText.

每次有按鍵被按下時onKeyPressObservable事件被觸發。但是你也可以依靠keyboard.connect(inputText)來自動的把一個虛擬鍵盤和一個輸入文本框連接起來,這個鍵盤將只在這個文本輸入框獲得焦點時出現,並且所有的按鍵按下事件將被發送到這個文本輸入框。

You can find a complete demo here: https://www.babylonjs-playground.com/#S7L7FE -

你可以在這裏找到一個完整的示例:

Containers

容器

The containers are controls used to host other controls. Use them to organize your UI. Containers has one specific property: container.background. Use it to define the background color of your container.

容器是用來主持其他被管對象的被管對象。使用他們來組織你的UI。容器有一個獨有的屬性:container.background.使用它來定義你的容器的背景顏色

Rectangle

矩形

The Rectangle is a rectangular container with the following properties:

矩形是一個具有以下屬性的長方形的容器

Property

Type

Default

Comments

thickness

number

1

Thickness of the border

邊框的厚度

cornerRadius

number

0

Size in pixel of each corner. Used to create rounded rectangles

用像素表示的每個邊角的尺寸。用來建立圓角矩形

Here is an example of a rectangle control: https://www.babylonjs-playground.com/#XCPP9Y#8 -

這裏是一個矩形被管對象的例子

Ellipse

橢圓

The Ellipse is a ellipsoidal container with the following properties:

橢圓是一種橢圓的具有以下屬性的容器

Property

Type

Default

Comments

thickness

number

1

Thickness of the border

邊框的厚度

Here is an example of an ellipse control: https://www.babylonjs-playground.com/#XCPP9Y#10 -

這裏是一個橢圓被管對象的例子

StackPanel

堆棧面板

The StackPanel is a control which stacks its children based on its orientation (can be horizontal or vertical). All children must have a defined width or height (depending on the orientation).

堆棧面板是一種基於排列方向(水平或豎直)來堆積子元素的被管對象。所有的子元素都必須具有一個定義好的寬度或高度(基於排列方向)

The height (or width) of the StackPanel is defined automatically based on children.

堆棧面板的高度(或寬度)基於子元素自動定義

Here is an example of a StackPanel: https://www.babylonjs-playground.com/#XCPP9Y#11 -

這裏是一個堆棧面板的例子

ColorPicker

拾色器

The color picker control allows users to set colors in your scene.

拾色器被管對象允許用戶在你的場景內設置顏色。

Whenever a user interacts with the color picker an observable is triggered (colorPicker.onValueChangedObservable) which returns the current value (Color3) of the color picker.

當用戶和拾色器交互時一個事件被觸發(colorPicker.onValueChangedObservable),它將返回拾色器當前的值(Color3)

The control is rendered using the following properties:

這個被管對象基於以下屬性渲染:

Property

Type

Default

Comments

size

string or number

"200px"

The size, width, and height property will always be the same value since the color picker can only be a square.

尺寸,寬度和高度屬性必須是相同的值因為拾色器必須是一個方塊

Here is an example of a color picker: https://www.babylonjs-playground.com/#91I2RE#1 -

這裏是一個拾色器的例子:

Helpers(Header?)

幫助

To reduce the amount of code required to achieve frequent tasks you can use the following helpers:

為了降低頻繁的任務所需的代碼數量,你可以使用如下的幫助

  • BABYLON.GUI.Control.AddHeader(control, text, size, options { isHorizontal, controlFirst }): This function will create a StackPanel (horizontal or vertical based on options) and will add your control plus a TextBlock in it. Options can also be used to specify if the control is inserted first of after the header. Depending on the orientation, size will either specify the widht or the height used for the TextBlock.

BABYLON.GUI.Control.AddHeader(control, text, size, options { isHorizontal, controlFirst }):這個方法將建立一個堆棧面板(基於選項確定水平還是豎直),然後將把你的被管對象和一個文本框一起放在這個堆棧面板裏面。同樣可以通過選項設置這個被管對象插入到標題的前面還是後面。根據方向,文本框的寬度或者高度尺寸也將被自動設定。

Focus management

焦點管理

The current focused control can be found using advancedDynamicTexture.focusedControl. You can also manually move the focus to a focusable control by calling advancedDynamicTexture.moveFocusToControl(control).

可以使用advancedDynamicTexture.focusedControl找到當前保有焦點的被管對象。你也可以人工的將焦點移動到一個可以獲得焦點的被管對象上,通過調用advancedDynamicTexture.moveFocusToControl(control)

Babylon.GUI官方文檔翻譯