如何使用 toDataURL() 方法将 Group 保存到 Image In Konvas.js,而不是整个舞台区域

How to use the toDataURL() method to save the Group to Image In Konvas.js, rather than the whole stage area

我想用toDataURL()方法来保存Group和Group中的所有形状,下面的图1是我的预期结果,但是我得到了一个意想不到的结果,如下图2,我该如何保存仅集团区域,而非整个舞台,

我的代码如下:

class Test1 extends React.Component{

constructor(props) {
    super(props)
    this.state = {
        image: new window.Image(),
    }
}

static defaultProps = {

}

componentDidMount() {

    this.state.image.setAttribute("crossOrigin", "anonymous");
    this.state.image.src = "https://vd.youniwote.com/homework/44evmey2cbd/submit/44evmey2cbe.jpg";
    this.state.image.onload = () => {
        // calling set state here will do nothing
        // because properties of Konva.Image are not changed
        // so we need to update layer manually
        this.imageNode.getLayer().batchDraw();
    };
}

render() {

    return (
        <div>
            <Button style={{top: 0, left: 0}} onClick={() => {
                console.log(this.group.toDataURL())
            }}>saveToImage</Button>
            <div style={{backgroundColor: '#e3e3e3'}}>
                <Stage
                    height={1000}
                    width={1000}
                    ref={node => {
                        this.stage = node;
                    }}
                >
                    <Layer
                        ref={node => {
                            this.layer = node;
                        }}
                    >
                        <Group
                            ref={node => {
                                this.group = node;
                            }}
                        >
                            <Text
                                x={300}
                                y={0}
                                text="test text"
                                fontSize={24}
                                fill='red'
                            />

                            <Image
                                draggable
                                x={200}
                                y={20}
                                image={this.state.image}
                                width={500}
                                height={500}
                                ref={node => {
                                    this.imageNode = node;
                                }}
                            >

                            </Image>
                        </Group>

                    </Layer>

                </Stage>
            </div>

        </div>
    )
}

}

如果有人回答这个问题,我会很感激

最近有相关修复。尝试将 Konva 更新到最新版本。

或者您需要为 toDataURL() 参数设置 xywidthheight

const url = this.group.toDataURL({x: group.x(), y: group.y(), width: 500, height: 520 })

演示:https://codesandbox.io/s/pkr5o2wpl7