Deep Sharma
Deep Sharma

Reputation: 3473

Unable to change image dynamically using fabric.js

i have 3(max 5) images placed on canvas using fabric.js, now i am trying to replace these images with an array having urls of new images. And finally i am generating image output but since images are loaded asyc so they are not rendered in the output(image). I have looked for so many solutions but nothing works

this is the code that i am using:

      var canvas_virtual = new fabric.Canvas('virtual_canvas');
      function GetOutput(){
               var exist_objects = canvas.getObjects();


            for (var k = 0; k < exist_objects.length; k++) {
               var obj = fabric.util.object.clone(exist_objects[k]);
               if(obj.name.indexOf("img_icon") > -1){
                   fnAddImageSave(obj.top,obj.left,obj.id,obj.propertyname,obj.tempPreviewData,obj.nutrientId,listIcons[k],canvas_virtual,obj.height);
                }
            }
            canvas_virtual.renderAll();
            console.log(canvas_virtual.toDataURLWithMultiplier("image/jpeg", 1));
         }

Definition of fnAddImageSave :

  function fnAddImageSave(top, left, image_id, property_name, previewData, nutrientValue, url,canvasObj,height)
    {

        var img = new Image(); //Equivalent: $(document.createElement('img'))
        var URL = url;

        //$('#add').append(img);


        var name = image_id;

        fabric.Image.fromURL(URL, function (oImg) {
            //oImg.set('left', PosX).set('top',PosY);
            oImg.height = height;
            canvasObj.add(oImg);
            canvasObj.renderAll();
        }, {
            "id": name,
            "name": name,
            "left": left,
            "top": top,
            "scaleX": .5,
            "scaleY": .5,
            "cornerSize": 5,
            "propertyname": property_name,
            "tempPreviewData": previewData,
            "nutrientId": nutrientValue
        });
    }

Upvotes: 1

Views: 1059

Answers (1)

Deep Sharma
Deep Sharma

Reputation: 3473

I brought the image to the HTML from server then i used those images to add them to canvas using fabricjs. It worked without any issue. below is the code that i used:

 imgElement = $("#add img[src$='/" + imgElement.defaultIcon.replace('\\', '/') + "']");
 $(imgElement[0]).attr('height', obj.height * obj.scaleY);
 var imgInstance = new fabric.Image(imgElement[0], {
                               "id": obj.id,
                               "name": obj.name,
                               "left": obj.left,
                               "top": obj.top,
                               "cornerSize": 5,
                               "propertyname": obj.propertyname,
                               "tempPreviewData": obj.tempPreviewData,
                               "nutrientId": obj.nutrientId
 });
canvas_virtual.add(imgInstance); 
canvas_virtual.renderAll();   

Upvotes: 1

Related Questions