Skip to content

Setting <Canvas style> #24

@haxiomic

Description

@haxiomic

It'd be very useful to set style to position the content in the page. I made a quick workaround utility but it is blocked by #23

Style should apply to the container div

import { useEffect } from "react";
import { useTwo } from "react-two.js";

export function TwoElementStyle({ style }: {
  style: Partial<CSSStyleDeclaration>;
}) {
  const { two } = useTwo();

  useEffect(() => {
    const domElement: HTMLElement | undefined = two?.renderer.domElement;
    const parentElement = domElement?.parentElement;
    if (!parentElement) return;

    const className = `two-style-${crypto.randomUUID()}`;
    const sheet = new CSSStyleSheet();
    
    sheet.insertRule(`.${className} {}`);
    Object.assign((sheet.cssRules[0] as CSSStyleRule).style, style);

    document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
    parentElement.classList.add(className);

    two?.fit();

    return () => {
      parentElement.classList.remove(className);
      document.adoptedStyleSheets = document.adoptedStyleSheets.filter(s => s !== sheet);
    };
  }, [two, style]);

  return null;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions