gpt4 book ai didi

javascript - 在 React 中从 Canvas context.getImageData 渲染 ImageData

转载 作者:行者123 更新时间:2023-11-30 15:16:31 32 4
gpt4 key购买 nike

在 React 组件中,我如何渲染使用 Canvas 创建的图像?

componentWillMount () {
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
canvas.width = 256
canvas.height = 256
// omitted canvas painting code
const image = context.getImageData(0, 0, canvas.width, canvas.height)
this.setState({image})
}

render() {
return ?
}

最佳答案

我不确定您是否可以直接在 render 方法中渲染它。但是如果你使用 componentDidMount/componentDidUpdate Hook ,如果你用状态设置它,你可以绘制它。

class Hi extends React.Component {
state = {};
componentWillMount () {
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
canvas.width = 256
canvas.height = 256
context.rect(20,20,150,100);
context.stroke();
const image = context.getImageData(0, 0, canvas.width, canvas.height)
this.setState({image})
}
componentDidMount() {
const context = this.refs.canvas.getContext('2d');
context.putImageData(this.state.image, 0, 0);
}
render() {
return <canvas ref="canvas" />
}
}

ReactDOM.render(<Hi />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

关于javascript - 在 React 中从 Canvas context.getImageData 渲染 ImageData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44383453/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com