繁体   English   中英

有没有办法使用 Canvas 通过 react.js 单击按钮来绘制一些东西?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM