简体   繁体   English

Fabric JS 缩放多个对象并将其居中在 canvas 上,而不缩放 canvas

[英]Fabric JS scaling multiple objects and center it on the canvas without scaling the canvas

Is it possible to scale down every object in a canvas (my image example contain about 10 objects) and center them without scaling the canvas?是否可以缩小 canvas 中的每个 object(我的图像示例包含大约 10 个对象)并将它们居中而不缩放 canvas? (The size of the canvas is the same in both the first and second image) (canvas 的尺寸在第一张和第二张图片中是一样的)

See image example the first image represent the original version, and the second image represent the desired version.参见图像示例,第一个图像代表原始版本,第二个图像代表所需版本。 Given some number, all objects are shrunk but their positioning are also tweaked so that their relative distances to each other are not disrupted, while maintaining centerism.给定一些数字,所有对象都会缩小,但它们的位置也会被调整,这样它们之间的相对距离就不会被打乱,同时保持中心主义。 The two images seem to be of different sizes, but they are the same size.这两个图像似乎大小不同,但它们的大小相同。

在此处输入图像描述

在此处输入图像描述

Yes, you can select every object and scale them to whatever dimension you need (if I understand your question).是的,您可以 select 每个 object 并将它们缩放到您需要的任何尺寸(如果我理解您的问题)。

   var selection = new fabric.ActiveSelection(canvas.getObjects(), { canvas:canvas });

        var sizeObj = resizer(
          { width: canvas.getWidth(), height: canvas.getHeight() },
          { width: selection.width, height: selection.height });

        selection.scaleToHeight(sizeObj.height)
        selection.center();

// routine from a stackoverflow contributer
resizer(canvas, imageObj) {
    var imageAspectRatio = imageObj.width / imageObj.height;
    var canvasAspectRatio = canvas.width / canvas.height;
    var renderableHeight, renderableWidth, xStart, yStart;

    // If image's aspect ratio is less than canvas's we fit on height
    // and place the image centrally along width
    if (imageAspectRatio < canvasAspectRatio) {
      renderableHeight = canvas.height;
      renderableWidth = imageObj.width * (renderableHeight / imageObj.height);
      xStart = (canvas.width - renderableWidth) / 2;
      yStart = 0;
    }

    // If image's aspect ratio is greater than canvas's we fit on width
    // and place the image centrally along height
    else if (imageAspectRatio > canvasAspectRatio) {
      renderableWidth = canvas.width
      renderableHeight = imageObj.height * (renderableWidth / imageObj.width);
      xStart = 0;
      yStart = (canvas.height - renderableHeight) / 2;
    }

    // Happy path - keep aspect ratio
    else {
      renderableHeight = canvas.height;
      renderableWidth = canvas.width;
      xStart = 0;
      yStart = 0;
    }
    return { x: xStart, y: yStart, width: renderableWidth, height: renderableHeight }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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