How to increase the selection area of ​​a tissue object?

Consider the following code:

var lineObj = new fabric.Line([120,200,320,200],{ stroke: '#000000', strokeWidth: 1 }); canvas.add(lineObj); 

This 1 pixel line is very difficult to choose because of its very small width. I would like to do here to increase my selection area. Like this:

Line corners

Is there a way I can do this?

+8
fabricjs
source share
2 answers

Yes, for this we have padding .

 var lineObj = new fabric.Line([120,200,320,200], { stroke: '#000000', strokeWidth: 1, padding: 20 }); canvas.add(lineObj); 

enter image description here

Did I mention that the fabric is flexible and powerful? :)

@markE Good solution! Glad you can easily go through the source code.

+10
source share

Bad news - there is no solution in the API / Good news - you can code your solution

The API does not provide a way to extend the bounding box of a row, so there is no way for the API to get a large selection for strings.

FabricJS is open source and well organized, and the source code itself has useful comments. Here is what I found ...

Line objects extend the Object object. The "object" has helper methods, and the object_geometry.mixin.js file is most suitable. There I discovered that a bounding box for any object is created using the getBoundingRect () method.

You asked: "Is there a way ..." like this:

So, to solve your problem, you have to override getBoundingRect () for strings and make it a little wider. This will automatically make the selection area of ​​your lines wider and easier. @Kangax, feel free to provide any simpler solution!

To get started, here is the source for getBoundingRect () from the source file object_geometry.mixin.js:

 getBoundingRect: function() { this.oCoords || this.setCoords(); var xCoords = [this.oCoords.tl.x, this.oCoords.tr.x, this.oCoords.br.x, this.oCoords.bl.x]; var minX = fabric.util.array.min(xCoords); var maxX = fabric.util.array.max(xCoords); var width = Math.abs(minX - maxX); var yCoords = [this.oCoords.tl.y, this.oCoords.tr.y, this.oCoords.br.y, this.oCoords.bl.y]; var minY = fabric.util.array.min(yCoords); var maxY = fabric.util.array.max(yCoords); var height = Math.abs(minY - maxY); return { left: minX, top: minY, width: width, height: height }; }, /** * Returns width of an object * @method getWidth * @return {Number} width value */ getWidth: function() { return this.width * this.scaleX; }, /** * Returns height of an object * @method getHeight * @return {Number} height value */ getHeight: function() { return this.height * this.scaleY; }, /** * Makes sure the scale is valid and modifies it if necessary * @private * @method _constrainScale * @param {Number} value * @return {Number} */ _constrainScale: function(value) { if (Math.abs(value) < this.minScaleLimit) { if (value < 0) return -this.minScaleLimit; else return this.minScaleLimit; } return value; } 
+4
source share

All Articles