7

我想知道有没有办法改变边界框图标,我阅读了fabric.js中的源代码,它为边界框生成方形框,但我想将其更改为圆形或更改为我的自定义外观。你能给我建议吗?

4

3 回答 3

9

自定义控件的最快方法是编写自己的_drawControl函数并使其与 fabricjs 标准兼容以覆盖它。请记住,每次渲染都会调用此函数 9 次,因此请尽量减少代码和绘图。此外,如果您修改上下文 (ctx),请记住使用.save并且.restore不要弄乱渲染管道。

FabricJs 将调用函数topleft为矩形做好准备,因此角将位于top + size/2and left + size/2,其中 size 为this.cornerSize

function newControls(control, ctx, methodName, left, top) {
  if (!this.isControlVisible(control)) {
        return;
      }
      var size = this.cornerSize;
      isVML() || this.transparentCorners || ctx.clearRect(left, top, size, size);
      ctx.arc(left + size/2, top + size/2, size/2, 0, 2 * Math.PI, false);
      ctx.stroke();
}

fabric.Object.prototype._drawControl = newControls;

function newControls(control, ctx, methodName, left, top) {
  if (!this.isControlVisible(control)) {
        return;
      }
      var size = this.cornerSize;
      this.transparentCorners || ctx.clearRect(left, top, size, size);
      ctx.beginPath();
      ctx.arc(left + size/2, top + size/2, size/2, 0, 2 * Math.PI, false);
      ctx.stroke();
}

fabric.Object.prototype._drawControl = newControls;
fabric.Object.prototype.cornerSize = 15;
var canvas = new fabric.Canvas('c');


canvas.add(new fabric.Rect({width:100, height:100, top:50, left:50}));
canvas.setActiveObject(canvas.getObjects()[0]);
<script type ="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<canvas id="c" width="400" height="400" style="border:1px solid #ccc"></canvas>

于 2016-01-27T09:06:33.087 回答
4

检查这些示例:

http://fabricjs.com/customization/

示例 2:

var canvas = new fabric.Canvas('c3');
  canvas.add(new fabric.Circle({ radius: 30, fill: '#f55', top: 100, left: 100 }));

  canvas.item(0).set({
    borderColor: 'red',
    cornerColor: 'green',
    cornerSize: 6,
    transparentCorners: false
  });
  canvas.setActiveObject(canvas.item(0));
于 2013-04-16T02:34:01.393 回答
0

这适用于最新版本的 fabricjs(截至目前为 4.4)。

您有一个在线示例http://fabricjs.com/controls-customization,它允许您对全局控件执行基本自定义。

它很简单:

fabric.Object.prototype.borderColor = 'blue';

例如,将边框颜色更改为蓝色。

另一个依赖于fabricjs 4 的演示,http ://fabricjs.com/custom-control-render ,包含允许您添加自定义控件的示例。把这个留给有兴趣的人。

于 2021-11-03T16:04:05.863 回答