gpt4 book ai didi

Fabricjs - 仅通过边框选择

转载 作者:行者123 更新时间:2023-12-03 18:29:21 26 4
gpt4 key购买 nike

我正在使用 Fabric.js 在 Canvas 上绘制一些矩形。默认行为是在矩形内单击以选择它。如何更改行为,使其仅在单击矩形边框时才被选中?

单击矩形内部而不是边框​​应该什么都不做。

您可以通过在 TradingView.com 图表上绘制一个矩形来查看此行为

它在结构中有一个选项,如果没有,我该如何实现它?

最佳答案

Fabric.js 使用 Object.containsPoint()确定鼠标事件是否应以对象为目标。反过来,此方法通过 Object._getImageLines() 计算对象的边缘。并检查鼠标指针的投影穿过这些线的次数。

下面的解决方案根据每个角的坐标计算额外的内边缘,因此自动处理对象缩放和旋转。

const canvas = new fabric.Canvas('c', {
enableRetinaScaling: true
})

const rect = new fabric.Rect({
left: 0,
top: 0,
width: 100,
height: 100,
dragBorderWidth: 15, // this is the custom attribute we've introduced
})

function innerCornerPoint(start, end, offset) {
// vector length
const l = start.distanceFrom(end)
// unit vector
const uv = new fabric.Point((end.x - start.x) / l, (end.y - start.y) / l)
// point on the vector at a given offset but no further than side length
const p = start.add(uv.multiply(Math.min(offset, l)))
// rotate point
return fabric.util.rotatePoint(p, start, fabric.util.degreesToRadians(45))
}

rect._getInnerBorderLines = function(c) {
// the actual offset from outer corner is the length of a hypotenuse of a right triangle with border widths as 2 sides
const offset = Math.sqrt(2 * (this.dragBorderWidth ** 2))
// find 4 inner corners as offsets rotated 45 degrees CW
const newCoords = {
tl: innerCornerPoint(c.tl, c.tr, offset),
tr: innerCornerPoint(c.tr, c.br, offset),
br: innerCornerPoint(c.br, c.bl, offset),
bl: innerCornerPoint(c.bl, c.tl, offset),
}
return this._getImageLines(newCoords)
}

rect.containsPoint = function(point, lines, absolute, calculate) {
const coords = calculate ? this.calcCoords(absolute) : absolute ? this.aCoords : this.oCoords
lines = lines || this._getImageLines(coords)
const innerRectPoints = this._findCrossPoints(point, lines);
const innerBorderPoints = this._findCrossPoints(point, this._getInnerBorderLines(coords))
// calculate intersections
return innerRectPoints === 1 && innerBorderPoints !== 1
}

canvas.add(rect)
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script>
<canvas id="c" width="400" height="300"></canvas>

关于Fabricjs - 仅通过边框选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60143667/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com