In this article, we are going to see how to enable or disable the selection of objects in a canvas in Fabric.js using the selection property. The canvas in Fabric.js is used as a wrapper over the native canvas object provided by HTML. It provides high-level access to the underlying canvas allowing it to have an object model, allow parsing for SVG files, and allowing the canvas to be interacted with in an intuitive manner.
Approach: To make it possible we are going to use a JavaScript library called Fabric.js. After importing the library, we will create the canvas block in the body tag. After this, we will initialize an instance of the canvas object provided by Fabric.js and set the selection mode needed for the canvas using the selection property.
Syntax:
fabric.Canvas(canvasElement, { selection: Boolean });
Parameters: This property accepts a single parameter as mentioned above and described below.
- selection: It is a boolean that specifies whether the selection of objects should be enabled or not on the canvas.
Example: The below example illustrates the use of Fabric.js Canvas selection property in JavaScript.
HTML
<!DOCTYPE html> < html > < head > <!-- Adding the FabricJS library --> < script src = </ script > </ head > < body > < div style="text-align: center; width: 500px;"> < h1 style = "color: green;" > neveropen </ h1 > < b > Fabric.js | Canvas selection Property </ b > </ div > < b >Selection Disabled</ b > < canvas id = "canvas" width = "500" height = "250" style = "border:1px solid #000000" > </ canvas > < b >Selection Enabled</ b > < canvas id = "canvas2" width = "500" height = "250" style = "border:1px solid #000000" > </ canvas > < script > let circle = new fabric.Circle({ radius: 30, }); let circle2 = new fabric.Circle({ radius: 30, }); // Initiate a Canvas instance let canvas = new fabric.Canvas("canvas", { // Disable selection // in this Canvas selection: false }); // Initiate a Canvas instance let canvas2 = new fabric.Canvas("canvas2", { // Enable selection // in this Canvas selection: true }); canvas.add(circle); canvas.centerObject(circle); canvas2.add(circle2); canvas2.centerObject(circle2); </ script > </ body > </ html > |
Output: