悬停

时间:2017-07-28 20:39:57

标签: javascript fabricjs

我尝试在用户悬停元素时添加标签:

var rect = new fabric.Rect({
    originX: 'top',
    originY: 'top',
    width: 150,
    height: 120,
    fill: 'rgba(255,0,0,0.5)',
    transparentCorners: true
});
var text = new fabric.Text('hello world', {
    fontSize: 30,
    originX: 'top',
    originY: 'top'
});

canvas.on('mouse:over', function(e) {
    var group = new fabric.Group([ rect, text ], {
    left: e.target.left,
    top: e.target.top
});
    canvas.add(group);
    canvas.renderAll();
});

canvas.on('mouse:out', function(e) {
    //e.target.set('fill', 'green');
    canvas.remove(group);
    canvas.renderAll();
});

但当mouse:out发射时,我得到了:

Uncaught ReferenceError: group is not defined
    at i.<anonymous> (can.js:38)
    at i.r (fabric.min.js:1)
    at i._fireOverOutEvents (fabric.min.js:3)
    at i.findTarget (fabric.min.js:3)
    at i.__onMouseMove (fabric.min.js:4)
    at i._onMouseMove (fabric.min.js:4)

如何使用悬停元素的左侧和顶部创建一个全局组,或者有更好的方法可以做到这一点?

2 个答案:

答案 0 :(得分:1)

<强>样本

&#13;
&#13;
var canvas = new fabric.Canvas('c');
var rect = new fabric.Rect({
    originX: 'top',
    originY: 'top',
    width: 150,
    height: 120,
    fill: 'rgba(255,0,0,0.5)',
    
});
var text = new fabric.Text('hello world', {
    fontSize: 30,
    originX: 'top',
    originY: 'top'
});
var group = new fabric.Group([ rect, text ], {
     left: 0,
     top: 0,
     selectable : false,
     visible: false,
});
canvas.add(group);
canvas.renderAll();

canvas.on('mouse:move', function(e) {
    var p = canvas.getPointer(e.e);
    group.set({
     left: p.x,
     top: p.y,
     visible: true
    });
    canvas.renderAll();
});

canvas.on('mouse:out', function(e) {
    group.set({
     visible: false
    })
    canvas.renderAll();
});
&#13;
canvas {
  border:2px dotted blue;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.17/fabric.min.js"></script>
<canvas id='c' width=400 height=400></canvas>
&#13;
&#13;
&#13;

你不需要在每个鼠标上创建组,你只需设置visible: true/false,所以根据它可以看到它。检查DEMO。

答案 1 :(得分:0)

group的范围是mouse:over事件本地的私有变量。尝试 正在删除var

&#13;
&#13;
var group = new fabric.Group([ rect, text ], {
&#13;
&#13;
&#13;     全局范围group
&#13;
&#13;
 group = new fabric.Group([ rect, text ], {
&#13;
&#13;
&#13;