Search code examples
javascriptkonvajskonva

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?


Solution

  • 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;