Search code examples
reactjshtml5-canvaskonvajsreact-konvakonvajs-reactjs

How to set HTML-id for a canvas element rendered with react-konva


I am using react-konva in a project to render HTML5-canvas elements:

import desktop_tea_1 from "./previews_desktop/tea_1.png";

const DesktopTea1 = () => {
    const [desktop_tea_1_const] = useImage(desktop_tea_1);
    return <Image image={desktop_tea_1_const} width={600} height={600}  />;
};

(...)

<Stage width={600} height={600}>
    <Layer ref="DesktopTea1">
        <DesktopTea1/>
    </Layer>
</Stage>

Now I want the HTML-output to have a id (myId) like:

<canvas width="600" height="600" id="myId"></canvas>

I can only find the konva-id but nothing to set a HTML-id.


Solution

  • It is better to use as less number of layers as possible. So I don't recommend to use many of them for your app.

    There is no Konva API to set id for canvas element of the layer. But you can do this manually:

    const App = () => {
      const layerRef = React.useRef(null);
      React.useEffect(() => {
        layerRef.current.getCanvas()._canvas.id = 'some-id';
      }, []);
    
      return (
        <Stage width={600} height={600}>
          <Layer ref={layerRef}>
            <DesktopTea1/>
          </Layer>
        </Stage>
      );
    }
    

    If you are not going to use too many layers css :nth-of-type() may work just fine.