[英]Is there a way to use Canvas to draw something on the click of a button with react.js?
我想使用我的<button>
組件調用一個特定的函數來使用 HTML5 Canvas 在我的 Canvas 上繪制。
這是文件的結構方式以及我如何傳遞道具 ->
我將 main 函數放在 App.js 中,通過 props 將其傳遞到我最中間的 MainPage.jsx 文件,然后通過 props 將 drawRectangle() 方法傳遞到最下面的 canvas.jsx 文件
在 Canvas.jsx 的最底層文件中 -
useEffect(() => {
const canvas = canvasRef.current;
canvas.width = "500";
canvas.height = "850";
let frameCount = 0;
let animationFrameId;
const c = canvas.getContext("2d");
//Function I want to call ->
drawRectangle(c, 'blue')
drawRectangle 方法放置在 App.js 文件(最上面的文件)中,按鈕在 MainPage.jsx 的中間文件中。
我是這樣通過的 - 在 App.js 中
handleRectangle=(c, color)=>
c.fillRect(0,0,100,100)
<MainPage onRectangle={handleRectangle} />
所以我想在我的 MainPage.jsx 文件中使用一個按鈕來調用這個函數,以便它在畫布上繪制一個矩形。 我不知道該怎么做。 因為 drawRectangle() 函數工作的唯一方法是將它放入 canvas.jsx 中的 useEffect() 中。
如果這有點令人困惑,我很抱歉,我在這方面有點初學者。
是的,您可以使用 refs
您只需在畫布 html 元素上放置一個 ref 並在您的點擊功能中使用它:
yourref.current.getContext("2d");
這是一個例子:
https://codesandbox.io/s/flamboyant-tdd-tne28?fontsize=14&hidenavigation=1&theme=dark
上面例子中的代碼粘貼在這里:
import React ,{useRef} from "react";
const DrawOnCanvas = ()=>{
const myref = useRef(null);
const _handleClick=()=>{
let ctx = myref.current.getContext("2d");
ctx.fillStyle="blue";
ctx.fillRect(100,100,32,32);
}
return <canvas width={500} height={350} onClick={_handleClick} ref={myref}></canvas>
}
export default function App() {
return (
<div className="App">
<DrawOnCanvas />
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
如果你想在另一個組件中調用繪圖功能,你可以將它作為道具傳遞
import React ,{useRef} from "react";
const DrawOnCanvas = (props)=>{
return <canvas width={500} height={350} onClick={props.clickHappened} ref={props.propRef}></canvas>
}
export default function App() {
const myref = useRef(null);
const _handleClick=()=>{
let ctx = myref.current.getContext("2d");
ctx.fillStyle="blue";
ctx.fillRect(100,100,32,32);
}
return (
<div className="App">
<DrawOnCanvas clickHappened={_handleClick} propRef={myref}/>
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
或者如果它真的是全球性的,你可以使用 localStorage 來存儲你的引用
你可以檢查_handleClick,只是為了檢查ref是否為空並且應該這樣做,應該不需要使用useEffect。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.