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 hard to select owing to its very small width. What I wish to do here is to increase its selection area. Like this:
Is there any way in which I can accomplish this?
Yes, we have padding
value for that.
var lineObj = new fabric.Line([120,200,320,200], {
stroke: '#000000',
strokeWidth: 1,
padding: 20
});
canvas.add(lineObj);
Did I mention Fabric is flexible and powerful? :)
@markE Nice solution! Glad you're finding it easy to walk through source code.
Bad news--no solution in API / Good news--you can code your solution
The API doesn't provide a way to expand the boundingbox of a line, so there's no API way to get a bigger selection area for lines.
FabricJS is open-source and well-organized and the source code itself has useful comments. Here's what I found...
"Line" objects extend the "Object" object. The "Object" has helper methods and the most pertinent is in the file object_geometry.mixin.js. In there, I found that the boundingbox for any object is being generated using the method getBoundingRect().
You did ask "Is there ANY way...", so here's that way:
So to solve your issue, you must over-ride the getBoundingRect() for lines and make it slightly wider. This will automatically make the selection area of your lines wider and more easily clicked. @Kangax, feel free to indicate any simpler solution!
To get you 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With