使图像完全适合 Konva Stage - Layer - Rect
Fit image completely inside Konva Stage - Layer - Rect
尝试在 Rect
的 Layer
和 fillPaternImage
属性 中使用 Rect
将背景图像放入 <Stage>
。背景图像确实占据了整个 space 舞台,但它被裁剪了。您如何 fit/cover 整个 space 舞台,同时保持图像(次要)的纵横比?
主要代码片段
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>
通过上面的代码,网页是这样的:
实际图像:
您可以使用 fillPatternScaleX
和 fillPatternScaleY
属性来更改图像的大小。
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}
>
);
尝试在 Rect
的 Layer
和 fillPaternImage
属性 中使用 Rect
将背景图像放入 <Stage>
。背景图像确实占据了整个 space 舞台,但它被裁剪了。您如何 fit/cover 整个 space 舞台,同时保持图像(次要)的纵横比?
主要代码片段
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>
通过上面的代码,网页是这样的:
实际图像:
您可以使用 fillPatternScaleX
和 fillPatternScaleY
属性来更改图像的大小。
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}
>
);