我正在通过下面的代码:
class Canvas extends React.Component {
componentDidMount() {
const canvas = this.refs.canvas;
const ctx = canvas.getContext("2d");
const img = this.refs.image;
img.onload = () => {
ctx.drawImage(img, 0, 0);
ctx.font = "40px Courier";
ctx.fillText(this.props.text, 210, 75); // THIS IS THE PLACE TEXT IS EMBEDDED INTO THE PICTURE
};
}
render() {
return (
<div>
<canvas ref="canvas" width={640} height={425} />
<img
ref="image"
alt="Stackoverflow56203352"
src={backImg}
className="hidden"
/>
</div>
);
}
}
我正在尝试将其转换为功能形式,由于缺少的替换,到目前为止,我的工作一直停滞不前getContext
。
即我在这里尝试:
const Canvas = ({}) => {
const canvas = useRef("")
const ctx = canvas.getContext("2d")
const img = useRef("")
img.onload = () => {
ctx.drawImage(img, 0, 0);
ctx.font = "40px Courier";
ctx.fillText(this.props.text, 210, 75); // THIS IS THE PLACE TEXT IS EMBEDDED INTO THE PICTURE
};
return (
<div>
<canvas ref="canvas" width={640} height={425} />
<img
ref="image"
alt="Stackoverflow56203352"
src={backImg}
className="hidden"
/>
</div>
);
}
没有削减。
完整的沙箱代码位于此位置
主要变化是您需要进行布线useEffect
,确保使用.current
来访问画布和图像的当前参考。
最初,我认为它只能与单个文件一起使用,useEffect
但是在重新加载页面时却失败了(我认为是由于图像被缓存并且没有onload
再次触发)。加一秒钟useEffect
就解决了(感谢Dennis Vash的帮助):
const Canvas = props => {
const canvas = useRef(null);
const image = useRef(null);
useEffect(() => {
const ctx = canvas.current.getContext("2d");
image.current.onload = () => {
ctx.drawImage(image.current, 0, 0);
ctx.font = "40px Courier";
ctx.fillText(props.text, 210, 75);
};
}, []);
useEffect(() => {
const ctx = canvas.current.getContext("2d");
ctx.drawImage(image.current, 0, 0);
ctx.font = "40px Courier";
ctx.fillText(props.text, 210, 75);
});
return (
<div>
<canvas ref={canvas} width={640} height={425} />
<img
ref={image}
alt="Stackoverflow56203352"
src={backImg}
className="hidden"
/>
</div>
);
};
另外,{}
在您的参考资料(而不是引号)周围使用。
在这里使用两个useRef
钩子更新了沙箱
尝试刷新页面几次
使用您的代码,图像上的文本消失。我在问题中给出了一个沙盒链接。
已更新...理想情况下,应将呈现代码移到单独的useCallback中,但现在可以使用了。
我将字体渲染添加回第一个的“ onload”中,
useEffect
并props.text
从第二个中删除了依赖性限制。谢谢!!很大的帮助