如何使用 Konva.Image 模拟背景位置行为?

How do I simulate background-position behavior with Konva.Image?

我有大约 50 张图片需要加载才能展示我的舞台。 我想减少请求的数量并加载一个包含我需要的所有图像的大精灵,然后在任何地方使用它,但要有正确的偏移量。就像我们在 CSS 中使用背景位置 属性.

所做的一样

尚未在文档中找到任何相关信息 - 这甚至可能吗?

您可以将精灵图像作为单个 JS 图像对象加载,然后将其分配给您需要的每个 Konva 图像对象,将每个 Konva 图像添加到其自己的组中,以便您可以使用组 clipFunc 来执行裁剪图像不需要的部分。您必须将图像的 x 和 y 移动图像中精灵的 x 和 y 的负值,才能在您需要的位置获得目标精灵。

工作示例here. The example just chops up a map image into even tiles but the gist is there. Sample pic below shows the tiles taken from the single map image. Map courtesy of Google Maps shows location of Pigcasso, the artist pig

对于该用例,您可以使用 crop attributes

对于每个 Konva.Image 实例,您只使用一个源图像元素。

const img = new Image();
img.onload = () => {
  const part1 = new Konva.Image({
    image: img,
    cropX: 0,
    cropY: 0,
    cropWidth: img.width / 2
    cropHeight: img.height
  });
  layer.add(part1);
  const part2 = new Konva.Image({
    image: img,
    cropX: img.width / 2,
    cropY: 0,
    cropWidth: img.width / 2
    cropHeight: img.height
  });
  layer.add(part2);
  layer.batchDraw();
}
img.src = url;