Created
June 2, 2020 07:32
-
-
Save TangerineCat/3720b2a9de4464eeab1902d0a17d00a0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useRef, useState } from 'react'; | |
import { Stage, Layer, Line} from 'react-konva'; | |
import Konva from 'konva'; | |
import '../styles/MyComponent.css'; | |
import {Mode} from './constants' | |
function DrawingCanvas() { | |
const stageRef = useRef<Stage>(null); | |
const stage = stageRef.current || new Stage({width: 600, height: 400}); | |
const [isPaint, setIsPaint] = useState(false); | |
const [mode, setMode] = useState(Mode.Brush); | |
const [lines, setLines] = useState([]); | |
const [lastLine, setLastLine] = useState<Konva.Line>(); | |
const [color, setColor] = useState("#ef740e"); | |
function onMouseDown() { | |
setIsPaint(true); | |
const pos = stage.getStage().getPointerPosition(); | |
if (pos == null) { | |
return; | |
} | |
const layer = new Konva.Layer(); | |
stage.getStage().add(layer) | |
setLastLine(new Konva.Line({ | |
stroke: color, | |
strokeWidth: 5, | |
points: [pos?.x, pos?.y], | |
globalCompositeOperation: mode === 'brush' ? 'source-over' : 'destination-out', | |
})); | |
if (lastLine) { | |
layer.add(lastLine); | |
} | |
} | |
function onMouseUp() { | |
if (!isPaint) { | |
return; | |
} | |
} | |
return ( | |
<Stage | |
ref={stageRef} | |
width={600} | |
height={400} | |
onMouseDown={onMouseDown} | |
onMouseUp={onMouseUp} | |
> | |
</Stage> | |
); | |
} | |
export default DrawingCanvas; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment