[英]React useRef on Canvas getting null or undefined
I am trying to reference a canvas DOM element to make the width of it the same as its parent without messing with the scale of the canvas.我正在尝试引用画布 DOM 元素以使其宽度与其父元素相同,而不会弄乱画布的比例。 When doing so I am getting a
Uncaught TypeError: _canvasRef$current.getContext is not a function
error and am not exactly sure how to fix it.这样做时,我得到一个
Uncaught TypeError: _canvasRef$current.getContext is not a function
error 并且不完全确定如何修复它。
Ive console logged a few things just to make the app run but the issue is within the useEffect
我控制台记录了一些事情只是为了让应用程序运行,但问题在于
useEffect
import SignaturePad from 'react-signature-canvas'
const canvasRef = useRef<HTMLCanvasElement>(null)
useEffect(() => {
const ctx: CanvasRenderingContext2D | null | undefined =
canvasRef.current?.getContext('2d')
const ctxContainer = document.getElementById('ctxContainer')
console.log('ctx: ', ctx)
// if (ctx && ctxContainer) {
// ctx.style.width = '100%'
// ctx.style.height = '100%'
// ctx.width = ctxContainer.clientWidth
// }
}, [])
const save = () => {
console.log('saved!')
}
console.log('canvasRef: ', canvasRef)
return (
<div id={`ctxContainer`} className={'signatureInput__option-draw'}>
<SignaturePad
ref={canvasRef}
canvasProps={{
className: 'signatureInput__option-draw__canvas',
}}
onEnd={save}
/>
</div>
)
Try this.尝试这个。
Note that you may still need to do some changes to following code to full fill your full requirement ( such as event handling when the user change the screen sizes. ) The following code will fix the issue you are facing right now.
请注意,您可能仍需要对以下代码进行一些更改以完全满足您的全部要求(例如用户更改屏幕尺寸时的事件处理。)以下代码将解决您现在面临的问题。
useEffect(() => {
if (canvasRef.current) {
const canvas = canvasRef.current.getCanvas();
const ctx = canvas.getContext('2d');
// do something with the canvas ref
if (ctx) {
ctx.canvas.width = window.innerHeight;
ctx.canvas.height = window.innerHeight;
}
}
}, []);
Try using getCanvas() .尝试使用 getCanvas() 。 i dont think getContext() is provided with the package
我不认为 getContext() 是随包一起提供的
function App() {
const canvasRef = React.createRef(null);
useEffect(() => {
const canvas = canvasRef.current;
console.log(canvas.current);
const ctx = canvas.getCanvas();
const ctxContainer = document.getElementById("ctxContainer");
console.log("ctx: ", ctx);
if (ctx && ctxContainer) {
ctx.style.width = "100%";
ctx.style.height = "100%";
ctx.width = ctxContainer.clientWidth;
}
}, []);
const save = () => {
console.log("saved!");
};
console.log("canvasRef: ", canvasRef);
return (
<div className="App">
<div id={`ctxContainer`} className={"signatureInput__option-draw"}>
<SignaturePad
ref={(ref) => {
canvasRef.current = ref;
}}
canvasProps={{
className: "signatureInput__option-draw__canvas",
}}
onEnd={save}
/>
</div>
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.