如何在fabric.js中设置样式

时间:2017-02-06 07:59:28

标签: javascript html5 canvas web fabricjs

帮助将样式设置为图片中的样式。几天,我尝试了选项,但不明白如何解决问题。

enter image description here

var rect = new fabric.Rect({
    left: 150,
    top: 200,
    originX: 'left',
    originY: 'top',
    width: 150,
    height: 120,
    angle: -10,
    fill: 'rgba(255,0,0,0.5)',
    transparentCorners: false
  });

1 个答案:

答案 0 :(得分:1)

VINET,

只需添加事件鼠标:over和mouse:out

canvas.on('mouse:over', function(e){
    if (e.target.type == 'rect'){
    e.target.set({strokeWidth: 5, stroke: 'red'});
  }
  canvas.renderAll();
});

canvas.on('mouse:out', function(e){
    canvas.forEachObject(function(o){
    o.set({strokeWidth: 0});
  });
  canvas.renderAll();
});

检查fiddle

<强>更新

如果你想分别突出显示每一面,你必须为这里的矩形创建自己的笔划:

function createPointsForLines(rectangle){
    let points = [];;
  var coordinates = rectangle.oCoords;
  points.push([coordinates.tl.x, 
        coordinates.tl.y, 
        coordinates.tr.x,
        coordinates.tr.y]);
  points.push([coordinates.tr.x, 
        coordinates.tr.y, 
      coordinates.br.x, 
      coordinates.br.y]);
  points.push([coordinates.br.x, 
        coordinates.br.y, 
      coordinates.bl.x, 
      coordinates.bl.y]);
  points.push([coordinates.bl.x, 
        coordinates.bl.y, 
      coordinates.tl.x, 
      coordinates.tl.y]);
  return points;
}

之后将这些笔画画成一条线:

for (var i in points){
    var line = new fabric.Line(points[i],{
    originX: 'center',
    originY: 'center',
    strokeWidth: 10,
    stroke: 'rgba(255,0,0,0)',
    transparentCorners: false
  });

canvas.add(line);
}

更新了fiddle