响应阶段存在对齐图像问题

问题描述 投票:0回答:0

我正在尝试使我的 Konva 舞台具有响应能力,我遵循了本教程: https://konvajs.org/docs/sandbox/Responsive_Canvas.html

我做了一些更改,我需要的是能够添加任何尺寸的任何图像,然后以最大可能的尺寸在画布上显示它,同时保持图像的比例。然后,如果调整编辑器的大小,我想相对调整所有内容的大小并将其保持在相同的位置。

首先我创建了舞台:

new Stage({
      container,
      width: container.width,
      height: container.height,
    } as StageConfig);

然后我创建图像对象:

    const imageRatio = Math.min(
        this.currentCanvasSize.width / this.imageSrcSize.getWidth(),
        this.currentCanvasSize.height / this.imageSrcSize.getHeight());

    const imageObj = new Konva.Image({
      image,
      width: this.imageSrcSize.getWidth(),
      height: this.imageSrcSize.getHeight(),
      x: ((this.stage.width() / 2) -
          ((this.imageSrcSize.getWidth() * imageRatio) / 2)) /
          imageRatio,
      y: ((this.stage.height() / 2) -
          ((this.imageSrcSize.getHeight() * imageRatio) / 2)) /
          imageRatio
    } as ImageConfig);

最后我缩放了一切:

    this.stage.scale({
      x: imageRatio,
      y: imageRatio
    });

然后我得到一个图像与中心对齐的编辑器,这正是我所期望的。

处理调整大小:

  private resizeStage() {
    const canvasSize = this.getCanvasSize();
    
    // Recalculates ratio to support new canvas size
    const imageRatio = Math.min(
        canvasSize.width / this.imageSrcSize.getWidth(),
        canvasSize.height / this.imageSrcSize.getHeight());

    this.stage.scale({x: imageRatio, y: imageRatio});
    this.stage.width(canvasSize.width);
    this.stage.height(canvasSize.height);
  }

然后我遇到的问题是我添加到舞台的图像对象不再居中。当放大编辑器时,图像会超出舞台,当缩小编辑器时,图像不再垂直对齐。

我该如何处理? 我考虑过可能向图像添加偏移量,但我想我也需要将其添加到所有其他对象。

还有其他解决办法吗?也许已经作为 Konva API 的一部分存在了?

konvajs konva
© www.soinside.com 2019 - 2024. All rights reserved.