如何为使用 react-konva 呈现的 canvas 元素设置 HTML-id
How to set HTML-id for a canvas element rendered with react-konva
我正在项目中使用 react-konva 来渲染 HTML5-canvas 元素:
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>
现在我希望 HTML-输出有一个 id (myId) 像:
<canvas width="600" height="600" id="myId"></canvas>
我只能找到 konva-id 但无法设置 HTML-id。
层数越少越好。所以我不建议在你的应用中使用它们中的许多。
没有 Konva API 为层的 canvas 元素设置 id。但您可以手动执行此操作:
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>
);
}
如果您不打算使用太多层 css :nth-of-type()
可能会很好。
我正在项目中使用 react-konva 来渲染 HTML5-canvas 元素:
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>
现在我希望 HTML-输出有一个 id (myId) 像:
<canvas width="600" height="600" id="myId"></canvas>
我只能找到 konva-id 但无法设置 HTML-id。
层数越少越好。所以我不建议在你的应用中使用它们中的许多。
没有 Konva API 为层的 canvas 元素设置 id。但您可以手动执行此操作:
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>
);
}
如果您不打算使用太多层 css :nth-of-type()
可能会很好。