Fabric JS悬停不起作用

时间:2019-04-24 16:06:06

标签: html5-canvas mouseevent fabricjs

我几乎没有元素(三角形),并且我希望能够在将鼠标悬停在每个元素上方时将它们突出显示(setShadow)(鼠标:悬停/鼠标:移动),并在鼠标悬停在上方时重置突出显示。

我尝试了this,但是它什么也没做。下面是我的代码:

var canvas = new fabric.Canvas('canvas');

var petal1 = new fabric.Triangle({
  width: 200,
  height: 300,
  fill: '#DBDBDB',
  left: 500,
  top: 350,
  angle: 200,
  strokeLineJoin: 'round',
  strokeWidth: 20,
  stroke: '#DBDBDB'
});

var petal2 = new fabric.Triangle({
  // same options as above
});

var petal3 = new fabric.Triangle({
  // same options as above
});

  canvas.on('mouse:over', function(e) {
    e.target.set('fill', 'red');
    canvas.renderAll();
  });

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


canvas.add(petal1, petal2, petal3);

我添加了console.log(e.target);,但没有打印任何内容。

1 个答案:

答案 0 :(得分:0)

您的代码段有效,并在设置属性之前检查目标。

演示

var canvas = new fabric.Canvas('canvas');
var options = {
  width: 100,
  height: 200,
  fill: '#DBDBDB',
  strokeLineJoin: 'round',
  strokeWidth: 20,
  stroke: '#DBDBDB'
};
var petal1 = new fabric.Triangle(options);
var petal2 = new fabric.Triangle(options);
var petal3 = new fabric.Triangle(options);

canvas.on('mouse:over', function(e) {
  if(e.target){
    e.target.set('fill', 'red');
    canvas.requestRenderAll();
  }
});

canvas.on('mouse:out', function(e) {
  if(e.target){
    e.target.set('fill', 'green');
    canvas.requestRenderAll();
  }
});

canvas.add(petal1, petal2, petal3);
canvas{
  border:1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.7.0/fabric.js"></script>
<canvas id="canvas" width="300" height="300"></canvas>