【问题标题】:Wrong position after center object using fabric js canvas使用fabric js画布中心对象后的错误位置
【发布时间】:2017-07-11 05:27:12
【问题描述】:

我在使用 FabricJS 的画布上有一个图像,加载图像后我调用 canvas.centerObject(img)。我有相同的图像缩放 2X,我正在尝试实现放大镜功能,一切正常,无需居中图像,但是一旦我调用 canvas.centerObject(img),更大的图像就不会显示在正确的位置。

    fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function (img) {
        img1 = img;
    img.set({
        width: originalWidth,
        height: originalHeight,
        evented: true,
        selectable: false
    });

    lens = fabric.util.object.clone(img);
    lens.set({
        width: scale * originalWidth,
        height: scale * originalHeight,
        clipTo: function (ctx) {
            ctx.arc(-this.left + x - this.width / 2, -this.top + y - this.height / 2, radius, 0, Math.PI * 2, true);
        }
    });

    canvas.add(img, lens);
    canvas.centerObject(img);//*******issue here****
});

canvas.on('mouse:move', function (e) {
    x = e.e.layerX;
    y = e.e.layerY;
    lens.set('left', -(scale - 1) * x);
    lens.set('top', -(scale - 1) * y);
    canvas.renderAll();
});

Please check on this fiddle

谢谢。

【问题讨论】:

    标签: javascript image image-processing html5-canvas fabricjs


    【解决方案1】:

    我重新对齐了较大的图像,以便在您调用 canvas.centerObject(img) 时正确显示。但是,您可能想重新考虑一下您的设计,以结合对象缩放,scale() - 当然,这取决于您的实现需求。

    这是一个更新的 JSFiddle 和调整后的代码:

    https://jsfiddle.net/rekrah/rfdxff5h/

      fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(img) {
        img1 = img;
        img.set({
          width: originalWidth,
          height: originalHeight,
          evented: true,
          selectable: false
        });
    
        lens = fabric.util.object.clone(img);
        lens.set({
          top: -225,
          left: 150,
          width: scale * originalWidth,
          height: scale * originalHeight,
          clipTo: function(ctx) {
            ctx.arc(-this.left + x - this.width / 2, -this.top + y - this.height / 2, radius, 0, Math.PI * 2, true);
          }
        });
    
        canvas.add(img, lens);
        canvas.centerObject(img);//******* issue no longer here****
      });
    
      canvas.on('mouse:move', function(e) {
        x = e.e.layerX;
        y = e.e.layerY;
        if (x > 150 && x < 750) {
          lens.set('left', -(scale - 1) * x + 300);
          lens.set('top', -(scale - 1) * y);
        }
        canvas.renderAll();
      });
    

    【讨论】:

    • 如果我理解,解决方案是基于这行代码:lens.set('left', -(scale - 1) * x + 300)。所以基本上我必须在大图像的左边添加 300 才能从小图像中实现 centerObject。如何动态计算该值 (300) 以使其适用于任何大小的图像??
    • 任何图像宽度的一半...但图像大小的四分之一需要用于镜头的左侧属性...但这也取决于您的画布大小。
    • @Arnel 这回答了你的问题吗?你介意标记为答案吗?如果您在实施时有任何其他问题,请告诉我。很高兴能提供更多帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 2020-11-12
    • 2016-07-07
    • 2018-12-12
    • 2016-05-26
    • 2015-06-21
    • 2017-08-07
    相关资源
    最近更新 更多