fabricjs甚至是组中对象的监听器

时间:2018-03-19 19:55:43

标签: fabricjs

var canvas = new fabric.Canvas('canvDraw');
var c = new fabric.Circle({
  radius: 10,
  left: 0,
  fill: '#fff',
  opacity: 0.1
});
c.hasControls = true; // enable to chaneg circle size
c.hasBorders = true;
c.setOpacity(100);
c.visible = true;
c.fill = '#000';

var text = new fabric.Text("Very long text data displayed on hover", {
  width: '50px'
});
var group = new fabric.Group([c, text], {
  left: left,
  top: top
});
canvas.add(group);

我希望在对象c悬停时显示文本等事件(组中的圆圈)。 试过c.on('老鼠:结束')但没有运气。

1 个答案:

答案 0 :(得分:0)

您需要使用subTargetCheck:true检查子目标,在鼠标悬停组检查时添加鼠标:将事件移动到画布并检查目标是否为圆圈然后显示文本设置为visible:false以隐藏。在mouseout上删除鼠标:从画布移动事件。

<强> 样本

&#13;
&#13;
var canvas = new fabric.Canvas('canvDraw');
var c = new fabric.Circle({
  radius: 100,
  left: 0,
  fill: '#a6ff00'
});

var text = new fabric.Text("Very long text data displayed \n on hover", {
  width: '50px',
  fill: 'green',
  visible: false
});
var group = new fabric.Group([c, text], {
  left: 20,
  top: 20,
  subTargetCheck:true,
  perPixelTargetFind:true
});
canvas.add(group);
group.on('mouseover',function(option){
  canvas.on('mouse:move',onMouseMove)
});
group.on('mouseout',function(option){
  onMouseMove();
  canvas.off('mouse:move',onMouseMove)
});

function onMouseMove(option){
 var textObj = group.getObjects()[1];
 if(option && option.subTargets[0] && (option.subTargets[0].type == 'circle')){
  if(textObj.visible) return;
  textObj.visible = true;
 }
 else {
  if(!textObj.visible) return;
  textObj.visible = false;
 }
 group.dirty = true;
 canvas.requestRenderAll();
}
&#13;
canvas{
 border:2px solid #000;
}
&#13;
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id='canvDraw' width=500 height=300></canvas>
&#13;
&#13;
&#13;