Fabricjs Counting Objects

Is there a way to count how many objects are already in the canvas using Fabric.js

    function addImage(imageName) {

    fabric.Image.fromURL('./image_path/' + imageName, function (image) {

        image.set({
            left: 10,
            top: 10,
            width: 100,
            height: 100,
            centeredScaling: true,
            lockUniScaling: true
        })


        canvas.add(image);
    });
};

and then you have jQuery:

    $('.click').on("click", function (e) {
    e.preventDefault;
    var imgId = $(this).attr('id');

    var number = $('canvas img').length;
    if (number == 5) {
        alert("You can add only 5 images");
    } else {
        addImage(imgId + ".png");
    }
});

Is there any way to count it?

+3
source share
2 answers

Try

var count = 0;//initial count
$('.click').on("click", function (e) {
    e.preventDefault;
    var imgId = $(this).attr('id');
    if (count > 5) { //check count of images added
        alert("You can add only 5 images");
    } else {
        addImage(imgId + ".png");
        count++;//increase count 
    }
});
+1
source

Here's a fixed version of how to read objects in fabricjs inside the canvas

var count = canvas.getObjects().length - 1;
$('.a').on("click", function (e) {
    e.preventDefault;
    var imgId = $(this).attr('id');


    if (count > 40) {
        alert("You can add only 40 images");

    } else {
        addImage(imgId + ".png");
        count++;
    }

});
+2
source

All Articles