Marvz73
Marvz73

Reputation: 93

Fabricjs JSON error when it going to loadFromDatalessJSON

I use the object clipTo to attach image to shape object, now when I save the canvas to JSON and store the data, it's working fine. Now when I load the JSON it give an error that this variable is undefined.

http://jsfiddle.net/efmbrm4v/2/

var clippingRect = new fabric.Rect({
    left: 100,
    top: 100,
    width: 100,
    height: 100,
    fill: 'transparent',
    opacity: 1
});
canvas.add(clippingRect);



var imgInstance = new fabric.Image(img, {
    width: instanceWidth,
    height: instanceHeight,
    top: (canvas.getHeight() / 2 - instanceHeight / 2),
    left: (canvas.getWidth() / 2 - instanceWidth / 2),
    originX: 'left',
    originY: 'top'
});
canvas.add(imgInstance);
imgInstance.clipTo = function(ctx) {
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);

    clippingRect.render(ctx); This part causing the error of undefined variable

    ctx.restore();
}

clippingRect.render(ctx); This part causing the error of undefined variable.

Upvotes: 0

Views: 838

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32889

The error is causing due to variable scoping. Since the code is running on window onload event, it loses reference for the rectangle­ (clippingRect) object and that­'s why it­'s throwing an error.

To make this work properly (on JSFiddle), you need to change the LOAD TYPE to No wrap - in <body>.

and, when working with your real project, place the script (JS code) before closing <body> tag.

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

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

var clippingRect = new fabric.Rect({
   left: 50,
   top: 50,
   width: 100,
   height: 100,
   fill: 'transparent',
   opacity: 1
});

fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(img) {
   img.set({
      left: 25,
      top: 25,
      width: 150,
      height: 150
   });
   canvas.add(img).setActiveObject(img);
   
   img.clipTo = function(ctx) {
      ctx.save();
      ctx.setTransform(1, 0, 0, 1, 0, 0);
      clippingRect.render(ctx);
      ctx.restore();
   }
   canvas.renderAll();
   
   var json = canvas.toJSON();
   c.loadFromJSON(json, c.renderAll.bind(c));
   c.renderAll();
});
body{display:flex}canvas{border:1px solid #ccc}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
<canvas id="canvas" width="200" height="200"></canvas>
<canvas id="c" width="200" height="200"></canvas>

also, on JSFiddle

Upvotes: 1

Related Questions