简体   繁体   中英

fabric js - objects in generated image have different positioning than the one in the canvas

I'm trying to use Fabric js to generate some images with text on it. But for some reason the positioning of the text in the generated image isn't consistent with the one in the canvas. Here's the image as it looks like in the canvas:

在此处输入图片说明

But the generated image looks like this:

在此处输入图片说明

The size I gave to the canvas is 881x640 and its the same with the output size I gave to the image.

Here's what I'm currently doing in my code.

I'm adding the background image into the canvas from the URL. But before I do, I first resize the image to be the same size as the canvas:

fabric.Image.fromURL(image_source, function(oImg) {
      oImg.width = canvas.width;
      oImg.height = canvas.height;
      canvas.add(oImg);
});

Then I'm sending the stringified result of the canvas.toJSON() call to the node js server to generate the image using AJAX:

$.post('http://host:1212', {'canvas': JSON.stringify(canvas.toJSON())});

In the server side I then load the objects and create the image:

var out = fs.createWriteStream(__dirname + '/uploads/' + file_name);

var body = '';
request.on('data', function(data){
    body += data;
});

request.on('end', function(){

  var request_params = qs.parse(body);

  //set to same size as the canvas on the client side
  var canvas = fabric.createCanvasForNode(881, 640);

  canvas.loadFromJSON(request_params.canvas, function(){
    canvas.renderAll();

    var stream = canvas.createPNGStream();
    stream.on('data', function(chunk){
      out.write(chunk);
    });

    stream.on('end', function(){
      //close filestream
      out.end();
  });
});

Any ideas where could have I gone wrong?

Maybe you should try to add canvas.calcOffset() :

fabric.Image.fromURL(image_source, function(oImg) {
      oImg.width = canvas.width;
      oImg.height = canvas.height;
      canvas.add(oImg);

      //HERE
      canvas.calcOffset()

});

I was having the same issue. It turns out there is a bug within fabric.js for rendering on node. Read about it here: https://github.com/kangax/fabric.js/issues/1754 .

To fix this, look at node_modules/fabric/dist/fabric.js - line 19376

_getLeftOffset: function() {
  // if (fabric.isLikelyNode) {
  //   return 0;
  // }
  return -this.width / 2;
}

Just like above, comment out the if(fabcir.isLikelyNode)...

This fixed it for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM