Search code examples
reactjsreact-konva

Fit image completely inside Konva Stage - Layer - Rect


Trying to put a background image into a <Stage> using a Rect inside a Layer and fillPaternImage property of Rect. The background image does take the entire space of the stage but it gets cropped. How do you fit/cover the entire space of the stage while preserving the aspect ratio of the image(secondary)?

Main Code Fragment

componentDidUpdate(props)
{
    const image = new window.Image();
    image.src = this.props.backgroundImage; // path to the image
    image.height = image.naturalHeight;
    image.width = image.naturalWidth;

    image.onload = () => {
        this.setState({
            fillPatternImage: image
        })
    }
}

<Stage
    width={1000}
    height={1000}
    style={{ border: '1px solid grey' }}
>
    <Layer>
        <Rect
            x={0}
            y={0}
            width={1000}
            height={1000}
            listening={false}
            fillPatternImage={this.state.fillPatternImage}
        >
        </Rect>
    </Layer>
</Stage>

Through the above code, the web page looks like this: enter image description here

Actual image: enter image description here


Solution

  • You can use fillPatternScaleX and fillPatternScaleY attributes to change the size of the image.

    const width = 1000;
    const height = 1000;
    
    const imageWidth = this.state.fillPatternImage?.width || width;
    const imageHeight = this.state.fillPatternImage?.height || height;
    
    const scaleX = width / imageWidth;
    const scaleY = height / imageHeight;
    const scale = Math.max(scaleX, scaleY);
    return (
      <Rect
        width={width}
        height={height}
        fillPatternImage={this.state.fillPatternImage}
        fillPatternScaleX={scale}
        fillPatternScaleY={scale}
      >
    );