【问题标题】:javascript remove multiple objects from canvas with unique attributejavascript从具有唯一属性的画布中删除多个对象
【发布时间】:2017-02-13 12:18:36
【问题描述】:

我正在使用结构 js 并在尝试删除组的父项时尝试删除组项。以下是我的代码。

jQuery(document).on('click', ".deleteBtn", function () {
    if (canvas.getActiveObject()) {
        var product_id = canvas.getActiveObject().get('product_id');
     }
        var canvasObj = canvas.getObjects();

    for(var i = 0; i < canvasObj.length; i++){

        var objRef = canvasObj[i];

        var accessoryId = objRef.get('accessory_product_id');

        var product_type = objRef.get('product_type');

        if(accessoryId == product_id && product_type == "accessory"){
            canvas.remove(objRef);
        }

    }
});

代码实际上正在工作,但没有删除所有具有相同 accessoryIdproduct_type 父项的项目,这是尝试删除的活动对象,并且其他两个项目正在正确删除。画布上只剩下两个项目。组中有所有 5 个项目。这些是图像。我找不到问题请帮忙。谢谢!

HTML 代码

<div id="content-tab-3" class="visualiser-product-category content-tab active">
    <ul>
        <li>
             <img src="http://localhost/green_live/wp-content/uploads/2016/07/Winter_Spice.png" class="visualizer-product-img" alt="Placeholder" data-quantity="1" data-product_type="parent" data-product_id="343">
              <img src="http://localhost/green_live/wp-content/uploads/2016/07/Winter-Spice-Desk-Floral.jpg" class="hide accessory-343">
              <img src="http://localhost/green_live/wp-content/uploads/2016/07/Winter-Spice-Garland.jpg" class="hide accessory-343">
              <img src="http://localhost/green_live/wp-content/uploads/2016/07/Winter-Spice-Tabletop.jpg" class="hide accessory-343">
              <img src="http://localhost/green_live/wp-content/uploads/2016/07/Winter-Spice-Wreath.jpg" class="hide accessory-343">
         </li>
    </ul>
</div>

【问题讨论】:

  • 请包含 html 标记
  • 已添加。它对此事的 html 标记并不重要,但正如你所问的那样。我想要在这里发生的是当使用单击data-product_type="parent" 中的删除按钮时,所有其他图像都需要从画布中删除。谢谢
  • 我指的是画布,而不是您页面中的随机 html!
  • 我在这里使用fabric.js 库。我在这里使用的唯一 canvas html 标记是

标签: javascript html canvas fabricjs


【解决方案1】:

您好,我在您的代码中注意到您尝试获取活动的对象 ID,但无论是否有活动对象,您继续循环,删除对象!! 也许,这会导致问题。

我将展示一个带有 forEach() 函数的示例,但只有在存在活动对象时才继续删除 对象

jQuery(document).on('click', ".deleteBtn", function () {

    //only if there is active object, do i delete objects
    if (canvas.getActiveObject()) {
        //get productId of active object
        var product_id = canvas.getActiveObject().product_id;

        //loop on the canvas objects
        canvas.getObjects().forEach(function (object) {

               if(object.accessoryId == product_id && object.product_type ==  "accessory"){
                canvas.remove(object);
              }
        });//end forEach
    }//end if
});//end 'click'

希望有所帮助,祝你好运。

【讨论】:

    猜你喜欢
    • 2010-09-17
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    相关资源
    最近更新 更多