跳到主要内容

<pc-button>

<pc-button> 添加按钮组件,让图像元素响应输入、触发 click,并通过染色或精灵切换显示状态。

用法

属性​

属性类型默认值说明
activeBoolean"true"是否响应按钮输入。false 显示未激活状态,不触发按钮事件,但元素仍接收并阻挡后方输入,详见禁用按钮
enabledBoolean"true"组件启用状态
fade-durationNumber"0"染色过渡毫秒数
hit-paddingVector4"0 0 0 0"按左、下、右、上扩展屏幕单位命中区域,不改变外观
hover-sprite-asset资源 ID-悬停状态的精灵资源 ID,仅精灵模式
hover-sprite-frameNumber"0"悬停精灵帧
hover-tintColor"0.75 0.75 0.75 1"悬停染色,仅染色模式
image实体引用-显示过渡的图像实体,默认自身,仅改变外观目标,输入仍来自按钮自身,详见图像实体
inactive-sprite-asset资源 ID-未激活状态的精灵资源 ID,仅精灵模式
inactive-sprite-frameNumber"0"未激活精灵帧
inactive-tintColor"0.25 0.25 0.25 1"未激活染色,仅染色模式
pressed-sprite-asset资源 ID-按下状态的精灵资源 ID,仅精灵模式
pressed-sprite-frameNumber"0"按下精灵帧
pressed-tintColor"0.5 0.5 0.5 1"按下染色,仅染色模式
transition-modeEnum"tint"tint 设置状态颜色,sprite 切换状态精灵。精灵模式缺少某状态资源时不显示图像,应为全部状态配置
染色替换图像颜色

染色替换图像颜色而非相乘,Alpha 也成为图像不透明度。因此默认灰色会让彩色按钮变灰、半透明按钮变实。应选择原色的浅深版本及正确 Alpha,详见染色。

示例​

按钮使用浅橙和深橙过渡。可悬停、按下,修改颜色或延长 fade-duration。下面脚本按后述方式监听 click:

实时示例
<pc-app>
<pc-asset src="https://developer.playcanvas.com/assets/fonts/arial.json" type="font" id="arial"></pc-asset>
<pc-scene>
<pc-entity name="camera">
<pc-camera clear-color="#1d1f2b"></pc-camera>
</pc-entity>
<pc-entity name="ui">
<pc-screen screen-space="true" scale-mode="blend" reference-resolution="640 320"></pc-screen>
<pc-entity name="button">
<!-- The image element provides the button's visuals and receives input -->
<pc-element type="image" anchor="0.5 0.5 0.5 0.5" pivot="0.5 0.5"
width="220" height="56" color="#ff8a3c" use-input></pc-element>
<pc-button transition-mode="tint" hover-tint="#ffa76d"
pressed-tint="#cc6e30" fade-duration="100"></pc-button>
<pc-entity name="label">
<pc-element type="text" anchor="0.5 0.5 0.5 0.5" pivot="0.5 0.5"
font-asset="arial" font-size="24" color="#1d1f2b" text="Click me"></pc-element>
</pc-entity>
</pc-entity>
</pc-entity>
</pc-scene>
</pc-app>
<script type="module">
import { whenReady } from '@playcanvas/web-components';

const button = await whenReady('pc-button');
const label = document.querySelector('pc-entity[name="label"] > pc-element');
let clicks = 0;
button.component.on('click', () => {
label.setAttribute('text', `Clicked ${++clicks} time${clicks === 1 ? '' : 's'}`);
});
</script>

在底层 Button 组件监听 click,使用 whenReady 等待初始化,不要同步查询,详见代码访问:

import { whenReady } from '@playcanvas/web-components';

const button = await whenReady('pc-entity[name="button"] > pc-button');
button.component.on('click', () => {
console.log('Button clicked!');
});

JavaScript 接口​

可以通过 ButtonComponentElement API创建和操作元素。

component 是底层 ButtonComponent,就绪前为 null,其余功能可通过它访问。

另请参阅​

  • <pc-element>:输入与过渡所需图像。
  • <pc-screen>:所属屏幕。
  • <pc-entity>:onclick 等指针事件也支持图像文本,但不提供按钮状态或命中扩展。
  • 按钮:状态、染色、精灵和事件。

示例:界面布局和滚动视图。