Fabricjs count objects

我的未来我决定 提交于 2019-12-10 20:49:15

问题


Is there any way to count how many objects are already in 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?


回答1:


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 
    }
});



回答2:


Here is fixed version how to count objects in fabricjs inside 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++;
    }

});


来源:https://stackoverflow.com/questions/21938358/fabricjs-count-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!