当它转到loadFromDatalessJSON时,Fabricjs JSON错误

时间:2017-06-25 10:59:00

标签: javascript canvas fabricjs

我使用对象clipTo将图像附加到形状对象,现在当我将画布保存到JSON并存储数据时,它工作正常。现在,当我加载JSON时,它会给出一个错误,即此变量未定义。

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); 此部分导致未定义变量的错误。

1 个答案:

答案 0 :(得分:1)

由于变量作用域而导致错误。由于代码在window onload事件上运行,因此它失去了对rectangle(clippingRect)对象的引用,而引发错误的原因。

为了使这项工作正常(在JSFiddle上),您需要将LOAD TYPE更改为No wrap - in <body>

并且,在处理您的真实项目时,请在关闭<body>标记之前放置脚本(JS代码)

ᴡᴏʀᴋɪɴɢᴡᴏʀᴋɪɴɢ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>

另外, JSFiddle