1

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.

  • With the current API, you can't set the id to canvas element directly. Why do you need it? – lavrton May 16 '19 at 14:25
  • I want to hide some layers based on viewport-width and want to keep all the responsive stuff in one place for clarity. I guess I could use the css :nth-of-type() selector but adding more and more images it will get very confusing. –  May 16 '19 at 21:29

1 Answers1

2

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.

lavrton
  • 18,973
  • 4
  • 30
  • 63
  • Great! `layerRef.current.getCanvas()._canvas.id = 'some-id';` solved my problem! Thanks a lot! –  May 22 '19 at 19:47