gpt4 book ai didi

javascript - 调整 Canvas 大小以适应容器

转载 作者:行者123 更新时间:2023-12-05 04:38:34 27 4
gpt4 key购买 nike

在尝试让我的 Canvas/Stage 调整大小并使其正确适合父容器时遇到一些问题。我发现了其他类似的帖子,虽然答案确实帮助我获得了新的屏幕尺寸,但它仍然不想适应容器,而是直接进入屏幕的边缘(这在示例中是预期的),使用左/右内容遍历父容器。

我已经尝试了很多不同的方法,但仍然找不到正确的方法,它不会超出父容器之外,并且 X/Y 比例不会偏离 Canvas 内形状的位置。对我来说最明显的方法是通过 CSS 对实际 Canvas /舞台设置约束,但这最终会导致缩放失败,使形状出现在 Canvas 之外。

在代码链接中,我包含了我尝试使用的hacky 方法,虽然在某些情况下设备屏幕较小时它看起来是正确的,但 Canvas 宽度仍会超出父容器。我不确定我是否想太多了,或者是否有更简单的方法来解决我的问题,任何帮助或提示都会很棒。

实时代码沙箱:https://codesandbox.io/s/white-surf-yc2vh

期望的结果图像:https://imgur.com/a/w0oXxG0

最佳答案

我认为您想要/需要的是调整 Canvas 大小,使其适合容器,同时保持您指定的纵横比。

您可以使用此函数调整一些矩形 (rect) 的大小,使其适合其他一些矩形 (container):

// fit a rect into some container, keeping the aspect ratio of the rect
export const fitRectIntoContainer = (rectWidth, rectHeight, containerWidth, containerHeight) => {

const widthRatio = containerWidth / rectWidth; // ration container width to rect width
const heightRatio = containerHeight / rectHeight; // ration container height to rect height

const ratio = Math.min( widthRatio, heightRatio ); // take the smaller ratio

// new rect width and height, scaled by the same ratio
return {
width: rectWidth * ratio,
height: rectHeight * ratio,
};
};

然后您可以调整 Canvas 的大小,使其适合容器:

const canvasSize = fitRectIntoContainer( 700, 600, size.width, size.height );
const canvasWidth = canvasSize.width;
const canvasHeight = canvasSize.height;

然后我猜你不再需要任何缩放(所以 scaleX 和 scaleY 可以都是 1 或未定义)

关于javascript - 调整 Canvas 大小以适应容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70571704/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com