Jastria Rahmat
Jastria Rahmat

Reputation: 911

In Konva, how to convert line with certain width to shape

Using Konva (konva-react), i render line using this component:

  const renderLine = (pathProps: CanvasPath | ActivePath, key?: number) => (
    <Line
      key={key}
      points={pathProps.points}
      stroke={pathProps.tool === "eraser" ? ERASER_COLOR : STROKE_COLOR}
      strokeWidth={pathProps.strokeWidth}
      tension={0.5}
      lineCap="round"
      globalCompositeOperation={
        pathProps.tool === "eraser" ? "destination-out" : "source-over"
      }
    />
  );

and here's my mouseEvent:


const handleMouseMove = useCallback(
    (e: Konva.KonvaEventObject<MouseEvent | TouchEvent>) => {
      if (!activePath?.isDrawing) return;

      const pos = e.target.getStage()?.getPointerPosition();
      if (!pos || !isPointInImage(pos.x, pos.y)) return;

      setActivePath({
        ...activePath,
        points: [...activePath.points, pos.x, pos.y],
      });
    },
    [activePath, isPointInImage]
  );

  const handleMouseUp = useCallback(() => {
    if (!activePath) return;

    const newPath: CanvasPath = {
      tool: activePath.tool,
      points: activePath.points,
      strokeWidth: activePath.strokeWidth,
    };

    setPaths(newPaths);
    setActivePath(null);
  }, [activePath, paths]);

nb: the set function is react state

konva line

I'd like, on mouse up, it'll be a single shape (or at least shapes in the same layer) that convert the width of the stroke into custom shape, like both the 'x' and the 'i'. Is it possible? Because, my goal is:

If it's in adobe illustrator the behavior is similar to expand to shape. So, It'll take the line, convert it to a shape alongside its stroke width and it will no longer be editable as a line.

Upvotes: 0

Views: 46

Answers (1)

Vanquished Wombat
Vanquished Wombat

Reputation: 9535

Assuming you take the same approach as adobe and make some button to fire code for 'expand to shape', you can make a custom shape to replace the Path shapes you have constructed.

A custom shape is a first-class shape in Konva, meaning it responds to all the usual events, z-index, etc, etc. See the Konva docs for information and examples.

The customshape.sceneFunc is where you code the drawing commands.

Upvotes: 1

Related Questions