在导出图像之前在 FabricJS 中隐藏背景

Hide Background in FabricJS before exporting Image

我想找出解决这个问题的最佳方法?单击按钮时,图像将作为 fabricjs 的背景加载 canvas...

我有另一个将 dataURL 保存为 PNG 的按钮...我试图在保存之前隐藏背景图像...

现在我已经将事件侦听器附加到背景图像以在单击导出按钮时隐藏自身,但是在导出图像之前背景图像不会隐藏...最好的订购方式是什么事件执行?

$("#export-image").click(function() {
   canvas.deactivateAll().renderAll();
   window.open(canvas.toDataURL('png'));
});


$('.background-img').on('click', function(e) {
   var imgURL = "http://placehold.it/350x150";
   $.ajax({
     url: imgURL,
     success: function(result) {
         fabric.Image.fromURL(imgURL, function(img) {
             $("#export-image").click(function() {
                 img.setOpacity(0);
                 canvas.renderAll();
             });
             img.set({width: canvas.width, height: canvas.height, originX: 'left', originY: 'top'});
             canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
              });

          }
    });

});

我会使用 fabricjs 事件而不是 dom 事件。

你是怎么做到的,导出dataURL的函数是在隐藏图片的函数之前注册的。还将不透明度设置为 0 意味着图像当前仅以透明方式呈现。浪费时间。

您无需在 toDataURL 之前调用 renderAll,它会自行调用它。

我会继续使用单击事件,我会使用 fabricjs 事件:

var bgImage;

function hideBg() {
    //i would not use setOpacity, this will make
    //it render transparent. wasted time.
    //canvas.backgroundImage.setOpacity(0);
    bgImage = canvas.backgroundImage;
    canvas.backgroundImage = null;
}

function showBg() {
    canvas.backgroundImage = bgImage;
}

$("#export-image").click(function() {
   canvas.on('before:render', hideBg);
   canvas.on('after:render', showBg);
   canvas.deactivateAll();
   window.open(canvas.toDataURL('png'));
   canvas.off('before:render', hideBg);
   canvas.off('after:render', showBg);
});


$('.background-img').on('click', function(e) {
   var imgURL = "http://placehold.it/350x150";
   $.ajax({
     url: imgURL,
     success: function(result) {
         fabric.Image.fromURL(imgURL, function(img) {
             img.set({width: canvas.width, height: canvas.height, 
                      originX: 'left', originY: 'top'});
             //let's save an handler just in case we mess up order in hide and show.
             bgImage = img
             canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
         });
      }
   });
});