Dylan w
Dylan w

Reputation: 2886

Konva - Export to High Quality Image and crop unwanted stage area

Currently I am exporting Konva as an image using the below when user clicks a button:


export const Demo = () => {
  const canvasRef = useRef();
  const signature = "Example text";
  const onSave = () => {
    const data = canvasRef?.current?.toDataURL({
      pixelRatio: 2
    });
  }

  return (<>
  <Stage
      ref={canvasRef}
      width={300}
      height={40}    >
      <Layer>
        <Text
          text={signature}
          verticalAlign="middle"
          fillStyle="#FF0000"
          fontSize={30}
          width={300}
          height={40}
        />
      </Layer>
    </Stage>
    <button onClick={onSave}/>
  </>)
}

The issue is, this will export the entire area of the Konva stage. Is there a way to export Konva where I can get the image from a specific area of the stage - not the entire stage. For example the image should only be of my text object.

Similar to https://gist.github.com/remy/784508 ?

Upvotes: 0

Views: 1544

Answers (1)

Vanquished Wombat
Vanquished Wombat

Reputation: 9525

The stage.toDataURL() method has a config object, explained here https://konvajs.org/api/Konva.Stage.html#toDataURL__anchor that allow you to export a targeted rectangle from the stage.

You can use this to reduce the excess space around the area intended for the exported image.

Upvotes: 4

Related Questions