簡體   English   中英

Fabric JS 縮放多個對象並將其居中在 canvas 上,而不縮放 canvas

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

是否可以縮小 canvas 中的每個 object(我的圖像示例包含大約 10 個對象)並將它們居中而不縮放 canvas? (canvas 的尺寸在第一張和第二張圖片中是一樣的)

參見圖像示例,第一個圖像代表原始版本,第二個圖像代表所需版本。 給定一些數字,所有對象都會縮小,但它們的位置也會被調整,這樣它們之間的相對距離就不會被打亂,同時保持中心主義。 這兩個圖像似乎大小不同,但它們的大小相同。

在此處輸入圖像描述

在此處輸入圖像描述

是的,您可以 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