Swoxy
Swoxy

Reputation: 11

How to make a responsive canvas for a basic image editor using react-konva?

I am building a basic image editor with react-konva. The canvas should:

For reference, I want to achieve functionality similar to the example shown in this link.

enter image description here

How can I make the canvas fully responsive and ensure the content scales proportionally?

import { Layer, Rect, Stage } from "react-konva";
import { useCanvas } from "./canvas-context";
import { ShapeRenderer } from "./shape-renderer";

const Canvas = () => {
    const { setSelectedId, stageRef, dimensions } = useCanvas();

    const deselectShape = (e: any) => {
        if (e.target === e.target.getStage()) setSelectedId(null);
    };

    return (
        <div
            id="canvas-container"
            className="relative flex h-full w-full flex-col items-center justify-center overflow-hidden"
        >
            <Stage
                id="konva-container"
                ref={stageRef}
                width={dimensions.width}
                height={dimensions.height}
                onMouseDown={deselectShape}
                onTouchStart={deselectShape}
                scaleX={dimensions.scale}
                scaleY={dimensions.scale}
            >
                <Layer>
                    <Rect
                        x={0}
                        y={0}
                        width={dimensions.width}
                        height={dimensions.height}
                        fill="black"
                        listening={false}
                    />
                    <ShapeRenderer />
                </Layer>
            </Stage>
        </div>
    );
};

Upvotes: 0

Views: 65

Answers (1)

Vinicius Dantas
Vinicius Dantas

Reputation: 1

You can obtain a similar effect by adding an eventListener with "resize" type like this:

useEffect(() => {
    const handleResize = () => {
      setWidth(window.innerWidth);
      setHeight(window.innerHeight);
    };
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

Inside the handleResize function, you will be able to get the new innerHeight and innerWidth of the window and adjust the content accordingly.

Upvotes: 0

Related Questions