Mikhail  Dudin
Mikhail Dudin

Reputation: 494

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

I have about 50 images that need to be loaded before I can show my stage. I'd like to reduce the number of requests and load one big sprite that contains all the images I need and then use it everywhere but with the right offset. Just like we do in CSS with the background-position property.

Haven't found anything about it in the docs - is this even possible?

Upvotes: 1

Views: 309

Answers (2)

lavrton
lavrton

Reputation: 20288

For that use case, you can use crop attributes.

For every Konva.Image instance you use just one source image element.

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;

Upvotes: 3

Vanquished Wombat
Vanquished Wombat

Reputation: 9525

You could load the sprites image as a single JS image object, then assign that to each Konva image object that you need, adding each Konva image to its own group so that you can use use the group clipFunc to do the clipping of the unwanted part of the image. You will have to move the x & y of the image by the negative of the x & y of the sprite in the image to get the target sprite where you need it.

Working example 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.

enter image description here

Upvotes: 1

Related Questions