首页 > 解决方案 > fabric.js:如何设置选择框和控件的笔触粗细?

问题描述

如何控制对象选择框和手柄上的笔触粗细

在 fabric.js 中,如何调整对象选择框和控制手柄的笔触粗细?

有许多自定义选项可用,但不清楚如何自定义笔画粗细。有没有可能,也许是通过间接的方式?

注意:属性selectionColor, selectionBorderColor,selectionLineWidth具有误导性......它们与尝试在画布上进行新的拖动选择时出现的临时选择框有关。一旦做出选择,它就会消失,然后您会看到带有控制句柄的持久对象选择框(我正在尝试自定义的东西)。

见链接:

http://fabricjs.com/customization

http://fabricjs.com/controls-customization

标签: fabricjs

解决方案


好的,这是一个两部分的解决方案:

https://codepen.io/MarsAndBack/pen/bGExXzd

对于选择框笔划粗细:

用于fabric.Object.prototype.set全局自定义任何对象选择。此外,borderScaleFactor已记录在案,但未包含在 fabric.js 自定义演示中:

fabric.Object.prototype.set({
  borderScaleFactor: 6
})

对于控制手柄行程粗细:

在这里,我们以不同的方式覆盖,实际上使用标准 HTML5 画布属性绘制新元素。通过这种方法,您还可以针对特定的控制手柄,甚至使用图像图标。

fabric.Object.prototype._drawControl = controlHandles
fabric.Object.prototype.cornerSize = 20

function controlHandles (control, ctx, methodName, left, top) {
  if (!this.isControlVisible(control)) {
    return
  }

  var size = this.cornerSize
  
  // Note 1: These are standard HTML5 canvas properties, not fabric.js.
  // Note 2: Order matters, for instance putting stroke() before strokeStyle may result in undesired effects.
  ctx.beginPath()
  ctx.arc(left + size / 2, top + size / 2, size / 2, 0, 2 * Math.PI, false);
  ctx.fillStyle = "pink"
  ctx.fill()
  ctx.lineWidth = 4 // This is the stroke thickness
  ctx.strokeStyle = "red"
  ctx.stroke()
}

SO代码片段:

const canvas = new fabric.Canvas("myCanvas")
canvas.backgroundColor="#222222"

this.box = new fabric.Rect ({
  width: 240,
  height: 100,
  fill: '#fff28a',
  myType: "box"
})

canvas.add(this.box)
this.box.center()


// Selection box border properties
// ----------------------------------------
fabric.Object.prototype.set({
  borderColor: "white",
  borderScaleFactor: 6
})


// Control handle properties
// ----------------------------------------
fabric.Object.prototype._drawControl = controlHandles
fabric.Object.prototype.cornerSize = 20

function controlHandles (control, ctx, methodName, left, top) {
  if (!this.isControlVisible(control)) {
    return
  }
  var size = this.cornerSize
  
  // Note 1: These are standard HTML5 canvas properties, not fabric.js.
  // Note 2: Order matters, for instance putting stroke() before strokeStyle may result in undesired effects.
  ctx.beginPath()
  ctx.arc(left + size/2, top + size/2, size/2, 0, 2 * Math.PI, false);
  ctx.fillStyle = "pink"
  ctx.fill()
  ctx.lineWidth = 4
  ctx.strokeStyle = "red"
  ctx.stroke()
}
<script src="https://pagecdn.io/lib/fabric/3.6.3/fabric.min.js"></script>
<canvas id="myCanvas" width="700" height="400"></canvas>


推荐阅读