1

I am desperately trying to work this out and all the information I have found isn't providing a solution. I have looked at the related question on StackOverflow and whilst I see the code, I cannot fix the issue.

I have created a failing JSFiddle. This is the code:

var canvas = window._canvas = new fabric.Canvas('c');

fabric.imagePlaceholder = fabric.util.createClass(fabric.Text, {
    type: 'imagePlaceholder',

    initialize: function(text, options) {

        options || (options = { });
        console.log('imagePlaceholder', text, options);
        this.callSuper('initialize', text, options);

        this.set('imageId', options.imageId || '');
        this.set('text', 'Loading ' + text || 'Loading...');
        this.set('type', 'imagePlaceholder');
    },

    toObject: function() {
        return fabric.util.object.extend(this.callSuper('toObject'), {
            imageId: this.get('imageId'),
            type: this.get('type'),
        });
    },

    _render: function(ctx) {
    this.callSuper('_render', ctx);
    ctx.font = '20px Arial';
    ctx.fillStyle = '#333';
    ctx.fillText(this.label, -this.width/2, -this.height/2 + 20);
    },
});

fabric.imagePlaceholder.fromObject = function (object, callback) {

    var _enlivenedObjects;
    fabric.util.enlivenedObjects(object.objects, function (enlivenedObjects) {
        delete object.objects;
        _enlivenedObjects = enlivenedObjects;
    });
    return new fabric.imagePlaceholder(_enlivenedObjects, object);
};

// Added or not it doesn't work :(
fabric.imagePlaceholder.async = true;

newObject = new fabric.imagePlaceholder('cat_image.jpg', {imageId:Date.now()});
canvas.add(newObject);

var json = window._json = canvas.toJSON();
console.log(json);

//Comment out the following to see the 'undefined' object being created..
//canvas.clear();
//canvas.loadFromJSON(json);

Essentially, I am creating a custom class so I can load the saved state from a server as JSON, load it into the canvas, then cycle through the objects, find the placeholders and replace them with images from our secure image service. The problem is, I cannot seem to overcome the async issue. Any ideas?

Thanks in advance,

Jonathon

Community
  • 1
  • 1
  • 1
    Images always load asynchronously. Install a load event handler and render them when they're ready. – Bergi Oct 07 '16 at 13:23
  • The issue isn't with the images - the issue is with the loadFromJSON - it is failing because of the custom class but for some reason everything I have tried as recommended by others / documentation is not providing an answer. – RideLikeTheWind Oct 08 '16 at 05:10

1 Answers1

0

I had same problem after a few hours looking into the code it turns out the

type: 'imagePlaceholder'

is converted into CamelCase in order to access the object when reading JSON data back in and so

fabric.imagePlaceholder = ...

Needs to be

fabric.ImagePlaceholder = ...

In order for it to work

John
  • 3,716
  • 2
  • 19
  • 21