改变背景不按预期工作

时间:2018-02-27 04:39:07

标签: fabricjs

我目前正在使用以下设置图像并根据需要替换它(使用fabricjs 1.7.22),但我正试图摆脱onclick=所以我选择用一个替换背景使用jQuery的id个数。

目前,事情看起来像这样:

我的HTML

<a onclick="replaceImage(oImg, '../images/1.png')" class="dropdown-item">Image Name 1</a>
<a onclick="replaceImage(oImg, '../images/2.png')" class="dropdown-item">Image Name 2</a>

我的JS

// Image Replacing
function replaceImage(oImgObj, imgUrl) {
  if (!isImageLoaded) return; //return if initial image not loaded
  var imgElem = oImgObj._element; //reference to actual image element
  imgElem.src = imgUrl; //set image source
  imgElem.onload = () => canvas1.renderAll(); //render on image load
}

// Default Image
fabric.Image.fromURL('../images/images/0.png'', function (img) {
  isImageLoaded = true;
  oImg = img.set({
    selectable: false,
    evented: false,
  }).scale(0.5);
  canvas1.add(oImg).renderAll();
  canvas1.sendToBack(oImg);
});

我现在正在尝试,但无法正常工作:

我的HTML

<a id="i0" class="dropdown-item">Image 1</a>
<a id="i1" class="dropdown-item">Image 2</a>

我的JS

$("#i0").click(function () {
  canvas1.setBackgroundImage('../images/0.png', canvas1.renderAll.bind(canvas1), {
    // Needed to position backgroundImage at 0/0
    originX: 'left',
    originY: 'top'
  });
});

$("#i1").click(function () {
  canvas1.setBackgroundImage('../images/1.png', canvas1.renderAll.bind(canvas1), {
    // Needed to position backgroundImage at 0/0
    originX: 'left',
    originY: 'top'
  });
});

当我点击后面的一个按钮时,没有任何反应,我没有得到任何错误,所以这就是我的循环。我能做错什么?

2 个答案:

答案 0 :(得分:1)

您在代码中使用的是jQuery而不是JavaScript。因此,将所有jquery代码放入就绪函数中,如下所示:

    $(document).ready(function(){
      //....jQuery code here
    });

此外,如果您的代码仍无法运行,请使用点击功能,如下所示:

     $(document).ready(function(){
        $('#i0').on('click', function () {
            // ....your code here
        })
     });

答案 1 :(得分:1)

您也可以使用此

    $(".page-content").css("background-image", "url('css/images/uimage.png')");

而不是

    canvas1.setBackgroundImage('../images/0.png', canvas1.renderAll.bind(canvas1), {
// Needed to position backgroundImage at 0/0
originX: 'left',
originY: 'top'
相关问题