Appearance
1. 事件处理(鼠标交互)
jtopo使用PointEvent处理各种输入设备(如鼠标、触摸、笔等)的交互;
提供统一的方式来处理交互,适用于不同输入类型的设备(电脑、手机、平板等)
TIP
- 一个全局的鼠标状态信息对象: stage.inputSystem
- 也可以在单独在某个Node或者Link对象上增加事件监听
2. 输入系统对象:inputSystem
inputSystem对象存储了当前鼠标的实时状态信息,例如:
鼠标按下的位置、鼠标在画布上的坐标、按下的是否右键、是否正在拖拽等。
2.1. 读取鼠标信息
js
// 获取inputSystem对象
let inputSystem = stage.inputSystem;
// 读取当前鼠标是否按下
let isPointerDown = inputSystem.isPointerDown;
// 读取鼠标指针在canvas上的的位置
let xInCanvas = inputSystem.x;
let yInCanvas = inputSystem.y;
// 读取鼠标指针在canvas上按下时的位置
let xInCanvasDown = inputSystem.pointerDownX;
let yInCanvasDown = inputSystem.pointerDownY;
// 读取鼠标指针世界坐标系(Layer中)的位置
let xInWorld = inputSystem.xInWorld;
let yInWorld = inputSystem.yInWorld;
// 读取当前鼠标选中的对象(Node 或者 Link)
let target = inputSystem.target;
if(target != null){
//...
}
2.2. 增加鼠标事件监听
js
stage.inputSystem.on('pointerup', function(){
console.log('鼠标画布位置', stage.inputSystem.x );
console.log('原始事件对象', stage.inputSystem.event);
});
2.3. 鼠标坐标转换
下面演示:
- 如何将世界坐标系中的位置转换成对象(node)坐标系中的位置
- 如何将对象(node)坐标系中的位置转换成世界坐标系中的位置
js
let inputSystem = stage.inputSystem;
inputSystem.on('pointerdown', ()=>{
let target = inputSystem.target;
if(target == null){
return;
}
// 将世界坐标系中的位置转换成对象内部坐标系中的位置
let xyInNodeLocal = target.worldToLocalXY(inputSystem.xInWorld, inputSystem.yInWorld);
console.log('inNodeLocal: ', xyInNodeLocal);
// 将对象内部坐标系中的位置转换成世界坐标系中的位置
let xyInWorld = target.localToWorldXY(0, 0);
console.log('inWorld: ', xyInWorld);
});
3. 给图元对象(Node、Link) 增加事件监听
代码示例:
js
// 全局性事件监听处理
stage.inputSystem.addEventListener('pointerdown', () => {
let target = stage.inputSystem.target;
if (target == null) {
console.log('没有点中任何对象');
return;
}
console.log('点中了一个对象:', target.x, target.y);
});
// 下面是单个对象的事件处理
// 鼠标或指针进入
node.addEventListener('pointerenter', function () {
console.log('pointerenter');
node.text = 'pointerenter';
});
// 鼠标或指针移动
node.addEventListener('pointermove', function () {
console.log('pointermove');
node.text = 'pointermove';
});
// 鼠标或指针离开
node.addEventListener('pointerout', function () {
node.text = 'pointerout';
console.log('pointerout');
});
// 按下
node.addEventListener('pointerdown', function () {
console.log('pointerdown');
node.text = 'pointerdown';
});
// 松开
node.addEventListener('pointerup', function () {
console.log('pointerup');
node.text = 'pointerup';
});
// 单击
node.addEventListener('click', function () {
node.text = 'click';
console.log('click');
});
// 双击
node.addEventListener('dblclick', function () {
console.log('dblclick');
node.text = 'dblclick';
});