reactjscanvasblueimpkonvajs

React Konva, blueimp-load-image uploaded Image rescaling


I'm trying to show an uploaded image inside a KonvaImage. The picture gets rescaled by blueimp-load-image with the following code.

const handleImageUpload = e => {
    const [file] = e.target.files;
    if (file) {
      loadImage(
        file,
        img => {
          setImage(img);
        },
        {
          orientation: true,
          maxWidth: innerWidth,
          maxHeight: innerHeight,
          downsamplingRatio: 0.2,
          pixelRatio: window.devicePixelRatio,
          imageSmoothingEnabled: true,
          imageSmoothingQuality: 'high',
          canvas: true,
        }
      );
    }
  };

This gives me the following value for the img when the pixelRatio is 1.25:

Img value

The height and width of the canvas get set to the innerWidth and innerHeight * 1.25 (PixelRatio) which I think is correct. And inside the style are the two values for real innerWidth and innerHeight of the screen.

But if I output this img in a <KonvaImage> element, the right side of the picture gets cut off, presumably because it only shows the first 939 pixels from left to right and cuts of the rest. Is it possible to let KonvaImage rescale the picture that it shows correctly.

It already works if I set the pixelRatio in loadImage to 1, because then the canvas just gets set to the real innerWidth and innerHeight values. However, these rescaled images look awful, especially on phone screens. So I want to know if there is a way to scale the pictures with KonvaImage so that they look good and have the right scaling.

This is the JSX code:

        <Stage
          width={window.innerWidth}
          height={window.innerHeight}
        >
          <Layer>
            <KonvaImage
              image={image}
            />
          </Layer>
        </Stage>

Solution

  • Konva is not reading styles from the generated canvas element. Only its real width and height. You just need to scale the image to match your pixelRatio:

    <KonvaImage
      scaleX={1 / pixelRatio}
      scaleX={1 / pixelRatio}
      image={image}
    />