Skip to content

1. 事件处理(鼠标交互)

jtopo封装了鼠标行为:

TIP

  1. 一个全局的鼠标状态信息对象: stage.inputSystem
  2. 也可以在单独在某个Node或者Link对象上增加事件监听

2. 输入系统对象:inputSystem

inputSystem对象存储了当前鼠标的实时状态信息,例如:
鼠标按下的位置、鼠标在画布上的坐标、按下的是否右键、是否正在拖拽等。

2.1. 读取鼠标信息

js
// 获取inputSystem对象
let inputSystem = stage.inputSystem;

// 读取鼠标指针在画布上的位置x
let xInCanvas = inputSystem.x;

// 读取鼠标最后一次按下时的坐标
let downX = inputSystem.mouseDownX;

// 读取当前鼠标是否在拖拽中
let isDraging = inputSystem.isDraging;

// 读取当前鼠标选中的对象(Node 或者 Link)
let target = inputSystem.target;
if(target != null){
    //... 
}
// 2.4.0 之前的版本: let target = inputSystem.pickedObject;


// 通过layer对象 读取当前鼠标在Layer中的坐标
let xInLayer = layer.mouseX;
let yInLayer = layer.mouseY;

2.2. 增加鼠标事件监听

js
stage.inputSystem.on('mouseup', function(){ 
    console.log('鼠标画布位置', stage.inputSystem.x ); 
    console.log('原始事件对象', stage.inputSystem.event);
});

2.3. 鼠标坐标转换

inputSystem.x 和 inputSystem.y 是鼠标在画布(Canvas上的坐标)

下面演示如何获取鼠标在Layer或者某个Node坐标系中的位置:
js
let inputSystem = stage.inputSystem;

inputSystem.on('mousedown', ()=>{
    // 将鼠标位置转成Layer坐标系中的位置
    let xyInLayer = layer.stageToLocalXY(inputSystem.mouseDownX, inputSystem.mouseDownY);
    console.log('inLayer: ', xyInLayer);

    // 鼠标在某个node坐标系中的位置
    let xyInNode = node.stageToLocalXY(inputSystem.mouseDownX, inputSystem.mouseDownY);
    console.log('inNode: ', xyInNode);
});

代码示例:

js
// 鼠标点击
node.addEventListener('click', function () {
    node.text = 'click';
    console.log('click');
});

// 鼠标双击
node.addEventListener('dblclick', function () {
    console.log('dblclick');
    node.text = 'dblclick';
});

// .addEventListener 有简写:.on 两者效果完全等价

// 鼠标进入
node.on('mouseenter', function () {
    console.log('mouseenter');
    node.text = 'mouseenter';
});

// 鼠标移动
node.on('mousemove', function () {
    console.log('mousemove');
    node.text = 'mousemove';

    let isMouseDown = stage.inputSystem.isMouseDown;
    if(isMouseDown){
        console.log('...')
    }
});

// 鼠标离开
node.on('mouseout', function () {
    node.text = 'mouseout';
    console.log('mouseout');
});

// 鼠标按下
node.on('mousedown', function () {
    console.log('mousedown');
    node.text = 'mousedown';
});

// 鼠标松开
node.on('mouseup', function () {
    console.log('mouseup');
    node.text = 'mouseup';
});

// 触摸开始
node.on('touchstart', function () {
    console.log('touchstart');
    node.text = 'touchstart';
});

// 触摸拖拽 
node.on('touchmove', function () {
    console.log('touchmove');
    node.text = 'touchmove';
});

// 触摸结束
node.on('touchend', function () {
    console.log('touchend');
    node.text = 'touchend';
});