如何在 Konvajs React 中模拟 CSS 之类的 Object-Fit Cover?

How can I simulate CSS like Object-Fit Cover in Konvajs React?

这在 DOM 中非常简单,因为我可以在 css 中执行对象匹配:覆盖,图像将裁剪并填充宽度和高度。但是在Konvajs中默认好像是填的。

这是我试过的方法:

  const [image] = useImage(content.img);

  if (image) {
    image.setAttribute('style', `object- 
    fit:cover;width:${content.width};height:${content.height}`);
  }

这行不通。

以防其他人正在寻找解决方案。

我能做到这一点的唯一方法是计算裁剪原始图像的位置。

const crop = () => {
  if (content.width > content.height) {
    const [cropX, cropY, cropW, cropH] = cropBasedOnWidth();
    if (cropY < 0) {
      const [cropX, cropY, cropW, cropH] = cropBasedOnHeight();
      return {x: cropX, y: cropY, height: cropH, width: cropW};
    }
    return {x: cropX, y: cropY, height: cropH, width: cropW};
  } else if (content.width < content.height) {
    const [cropX, cropY, cropW, cropH] = cropBasedOnHeight();

    if (cropX < 0) {
      const [cropX, cropY, cropW, cropH] = cropBasedOnWidth();
      return {x: cropX, y: cropY, height: cropH, width: cropW};
    }
      return {x: cropX, y: cropY, height: cropH, width: cropW};
    } else {
      return undefined;
    }
  }

const cropBasedOnWidth = () => {
 const cropW = content.naturalWidth;
 const cropH = cropW / content.width * content.height;
 const cropX = content.naturalWidth / 2 - cropW / 2;
 const cropY = content.naturalHeight / 2 - cropH / 2;
 return [cropX, cropY, cropW, cropH];
}

const cropBasedOnHeight = () => {
  const cropH = content.naturalHeight;
  const cropW = cropH / content.height * content.width;
  const cropX = content.naturalWidth / 2 - cropW / 2;
  const cropY = content.naturalHeight / 2 - cropH / 2;
  return [cropX, cropY, cropW, cropH];
}
...
return <Image crop={crop()} ... />

不知道有没有更好的方法