Using Fabric JS to create a group of multiple objects

Can Fabric JS allow for grouping all objects on the canvas with a click event?

Answer №1

Absolutely! You can group all the canvas objects with a simple click event. Check out this example where I demonstrate creating three objects and grouping them upon clicking.

var canvas = new fabric.Canvas('c');
canvas.backgroundColor = 'yellow';

//create circle object
 var circle = new fabric.Circle({
                  radius: 20, 
                  fill: 'red', 
                  left: 100, 
                  top: 100
                });
            canvas.add(circle);


//create square object
var square = new fabric.Rect({
              left: 130, 
              top: 140,
              fill: 'green',
              width: 40,
              height: 80
            });
            canvas.add(square);

canvas.renderAll();


$('#groupthem').on('click', function(event) {
    groupthem();
 });


var site_url =  'http://fabricjs.com/assets/1.svg';

fabric.loadSVGFromURL(site_url, function(objects) { 
          var group = new fabric.PathGroup(objects, { 
          left: 165, 
          top: 100, 
          width: 295, 
          height: 211 
        }); 
        canvas.add(group); 
        canvas.renderAll(); 
          }); 


function groupthem (){

    var objs = [];
    //get all the objects into an array
    objs = canvas._objects.filter(function(obj){
        return obj;
    });

    //group all the objects 
     var alltogetherObj = new fabric.Group(objs,{
                top:200,left:250,
                originX:'center',
                originY:'center'});


    //clear previous objects
    canvas._objects.forEach(function(obj){
        obj.remove();
    });

    canvas.add(alltogetherObj);
    alltogether.setCoords(); 
    canvas.renderAll();
}

live jsfiddle : http://jsfiddle.net/tornado1979/y6fqj8go/

https://i.sstatic.net/zkbtW.png

hope helps, good luck.

New updated fiddler link:http://jsfiddle.net/yogeshwari/sezxhqc4/1/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Running a local project with the help of the Express framework

// Setting up the configuration for serving files from the source directory var express = require('express'); // Importing express module var path = require('path'); // Importing path module var open = require('open'); // Imp ...

Challenges related to using the require() method in JavaScript

I've been encountering an issue while trying to run the JavaScript client for the Tumblr API from their Github repository. The error message I keep getting is "require not defined" which has led me on a hunt across various forums and websites, includi ...

REACT performance impacted by slow array filtering

I have a custom listbox feature, where a div holds a vertical list of other div elements. There is also an input field for searching within the list. While it works fine with small data sets, it becomes extremely slow with large amounts of data. In additi ...

Interaction between elements in Object3D

I have a collection of objects grouped together in Object3D and I'm attempting to detect when they are clicked on. My scene has dimensions of 600x400, my camera is part of a three-object, and the code for handling events looks like this: function onD ...

My confidential environment variables are being inadvertently revealed to the client by Next.js

I am encountering a problem with my project in which an environment variable is being revealed to the browser. Despite the documentation stating that only environment variables prefixed with NEXT_PUBLIC_ should be accessible in the browser environment, all ...

Acquire information using Vue through HTTP requests based on Router parameters

I have been searching for a solution to this issue and even referred to the example provided on the Vue Router documentation, but I am still encountering difficulties. My goal is to make an HTTP call when a component loads initially, then monitor the route ...

The Google Drive API in Node.js is notifying the deletion of files

I encountered an issue with the Google Drive API in my application. Even after deleting files from Google Drive, the listfiles function still returns those deleted files. Is there a solution to prevent this from happening? Below is the function of my API: ...

Troubleshooting Date Errors in Typescript with VueJS

Encountering a peculiar issue with Typescript while attempting to instantiate a new Date object. <template> <div> Testing Date</div> </template> <script lang="ts"> import Vue from "vue"; export default Vue.extend({ name: ...

I am having trouble with the browser detection not accurately identifying the browser I am currently using

Currently, I am working on a JavaScript code that will simply display the name of the browser being used to view the web page. Despite me using Safari, none of the navigators seem to recognize it as the current browser. The information displayed in my brow ...

The window.onload event is failing to trigger on mobile devices, although it is functioning properly on desktop. (using react js

Thank you for taking the time. Now, let's dive into the main topic: I have a scenario where I need to execute one of two functions based on a boolean value at the start. The decision is made using window.onload. This code works perfectly on desktop b ...

Transform HTML content into a PDF document with page breaks

Currently, I am developing a function that involves an HTML template. The purpose of this function is to generate a dynamic template and convert it into a PDF. So far, I have been able to achieve this using the following code: var output = ''; ...

methods to add an object to formData in vuejs

I am having trouble appending an object to FormData using Axios. I do not want to send data by JSON.stringify() data () { return { product: { title: '', description: '', properties: { ...

Interactive Chart with Angular for Multiple Selections

I have a single page with a list menu By utilizing the list menu, I am able to generate various types of charts such as line chart, bar chart, pie chart, and more. However, I would like the previously selected charts, like the line chart, pie chart, etc. ...

Customizing blockquote styling in QuillJS with a unique class

Currently, I am exploring a method to include a custom class when the user selects the blockquote toolbar button. When the blockquote is clicked, it generates the following element: <blockquote class="ql-align-justify">this is my quoted tex ...

I can't seem to figure out which of these 4 statements is free of syntax errors

Can you identify which code block does not contain a syntax error? Out of the 4 options below, one of them is free from any syntax mistakes. alert("hello "+3+" times); alert("hello "+3 times); alert("hello +3+ times"); alert("hel ...

The functionality of the `next-auth` signOut button click does not seem to accept a variable as input, although

The Nav.jsx component code provided is working as intended. In this implementation, clicking the 'Sign Out' button will redirect the application to http://localhost:3000. 'use client' import { signOut } from 'next-auth/react&apos ...

The UseEffect hook continues to run even if the dependency (router.query) remains the same

useEffect(() => { console.log('applying filter'); const updatedFilters = { status: { values: { label: router.query.status, value: router.query.status }, }, // Add additional filter properties here... }; ...

How to target the last child in Flexbox using CSS order property

Is there a way to correctly detect the last child after rearranging divs using flex order? Even though I have set the order in the CSS, it is still recognizing the last child based on the DOM tree. Since the items are dynamic, we can't rely on nth-chi ...

How can values be passed to child components in Vue when using component tags for dynamically switching components?

Is there a way to pass values to children components in Vue when using the component tag? It appears that I am unable to pass values to a child component using the component tag without using v-if: <component :is="showNow"></component> ...

Issues with retrieving a result object from a MySQL query in NodeJS

I've been working on creating a logging system in NodeJS with a MySQL database. To establish the connection, I use the following code: const con = mysql.createConnection({ host : 'localhost', user : 'dbuser', passwor ...