We can create a Polygon object by creating an instance offabric.Polygon. A polygon object can be characterized as any closed shape consisting of a set of connected straight line segments. Since it is one of the basic elements of FabricJS, we can also easily customize it by applying properties such as angle, opacity, etc. FabricJS provides us with an extensive set of events that we can use to create different effects.
Since we want the changes to occur on mouseover, we will use themouse:moveevent that fires when the mouse is moved. Our second requirement is to highlight an object, this can be achieved by using theopacityproperty, however, when there are many objects on the canvas and we want to highlight the object that is hovering over it, We need to use theforEachObjectmethod. This method runs a for-each loop for the given function, thereby executing it for each object.
forEachObject( callback: function, context: object ): Self
callback- This property accepts afunctionthat takes the current object as the first argument, the index as the second argument, and An array of all objects as the third one.
context- This property accepts anObjectthat represents the context in which the callback function was called.
Let's look at a code example to see how to add a highlight effect when there is only one object on the canvas. We have attached themouseoverandmouseoutevents to the polygon object (in this case, the triangle).mouseoverExecuted when the mouse moves over the object,mouseoutExecuted when the mouse hovers outside the object. As soon as we move the cursor over the element, its opacity will change from 0.5 to 1 and vice versa.
Displaying highlight effect with only one object
You can see that the object is being highlighted when the cursor is moved onto the element
In this example, we will see how to highlight an object when the mouse is hovering over it. Every time the mouse moves, themouse:moveevent is triggered. Here we use the mathematical distance formula to calculate the distance between two points in the coordinate plane through the "x" and "y" positions of the mouse pointer. This distance is then divided by 50, which is an arbitrary number that makes (dist/50) the fraction smaller (we know that as the denominator gets larger, the fraction gets smaller), so that when it is divided by 1, we get a The value is larger and the opacity increases.
Displaying highlight effect with multiple objects
You can see that an object is being highlighted only when the cursor is moved onto the element and is depended on the distance
In this tutorial, we use two simple examples to demonstrate how to use FabricJS to highlight objects when the mouse is hovering over them.
The above is the detailed content of How to highlight an object when the mouse is over it using FabricJS?. For more information, please follow other related articles on the PHP Chinese website!