如何使用组上的mouseover / mouseout事件处理填充切换

时间:2019-01-29 22:41:25

标签: konvajs

在jquery中,我们为此进行了切换。

如果我要进行jQuery DIY,则将“ on”和“ off”填充色隐藏在元素的“ data”属性中,并根据需要检索每种颜色。

什么是在Konva中实现鼠标悬停填充颜色切换的有效方法?

示例:假设我有一个图层,并且在此图层上有一个包含矩形的组。通过将鼠标悬停时更改其填充颜色并在mouseexit时恢复为正常状态,鼠标悬停和mouseout切换程序可以突出显示矩形。

rect.on('mouseover', function(evt){
  var shape = evt.target;
  // Uh-oh, I need to stash the current fill color somewhere 
  shape.fill('lime');

})
rect.on('mouseexit', function(evt){
  var shape = evt.target;
  shape.fill('that_stashed_fill_color');  // < how to get the stashed val and from where ?
})

有什么想法吗?

编辑:我自己的尝试是使用

rect.on('mouseover', function(evt){
  var shape = evt.target;
  $(shape).data('bgColor', shape.fill()); // stash current in data
  shape.fill('lime');    
})

rect.on('mouseexit', function(evt){
  var shape = evt.target;
  shape.fill($(shape).data('bgColor'));  // get the stashed val from jq data
})

这是可行的,但是使用jq包装器感觉就像是要避免的开销。

1 个答案:

答案 0 :(得分:1)

您几乎可以在Konva节点中使用任何自定义属性(确保您不与现有属性重叠,因此不会出现意外结果)。设置-shape.setAttr('anyAttibute', anyValue);得到-shape.getAttr('anyAttibute');

您可以这样做:

rect.on('mouseenter', function(evt){
  var shape = evt.target;
  shape.setAttr('oldFill', shape.fill());
  // set new fill
  shape.fill('lime');
  shape.getLayer().batchDraw();
})
rect.on('mouseleave', function(evt){
  var shape = evt.target;
  shape.fill(shape.getAttr('oldFill')); 
  shape.getLayer().batchDraw();
})

但是我个人更喜欢使用它:


const FILL_COLOR = 'red';
const HIGHLIGHT_COLOR = 'lime';

shape.fill(FILL_COLOR);
shape.on('mouseenter', function(evt){
  shape.fill(HIGHLIGHT_COLOR);
})
shape.on('mouseleave', function(evt){
  shape.fill(FILL_COLOR); 
})