|
1 | | -import React from 'react'; |
| 1 | +import React, { MouseEvent, useRef, useState } from 'react'; |
2 | 2 |
|
3 | 3 | const Screen = () => { |
| 4 | + const canvasRef = useRef<HTMLCanvasElement>(null); |
| 5 | + |
| 6 | + const [mouse, setMouse] = useState({ |
| 7 | + startX: 0, |
| 8 | + startY: 0, |
| 9 | + }); |
| 10 | + const [draging, setDraging] = useState(true); |
| 11 | + |
| 12 | + const handleMouseDown = (ev: MouseEvent) => { |
| 13 | + setMouse({ |
| 14 | + startX: ev.pageX - (canvasRef.current?.getBoundingClientRect().left || 0), |
| 15 | + startY: ev.pageY - (canvasRef.current?.getBoundingClientRect().top || 0), |
| 16 | + }); |
| 17 | + |
| 18 | + setDraging(true); |
| 19 | + }; |
| 20 | + |
| 21 | + const handleMouseMove = (ev: MouseEvent) => { |
| 22 | + if (!draging) { |
| 23 | + return; |
| 24 | + } |
| 25 | + |
| 26 | + const ctx = canvasRef.current?.getContext('2d'); |
| 27 | + |
| 28 | + if (ctx) { |
| 29 | + const width = |
| 30 | + ev.pageX - |
| 31 | + (canvasRef.current?.getBoundingClientRect().left || 0) - |
| 32 | + mouse.startX; |
| 33 | + const height = |
| 34 | + ev.pageY - |
| 35 | + (canvasRef.current?.getBoundingClientRect().top || 0) - |
| 36 | + mouse.startY; |
| 37 | + |
| 38 | + ctx.clearRect(0, 0, 1000, 1000); |
| 39 | + ctx.fillStyle = 'red'; |
| 40 | + ctx.fillRect(mouse.startX, mouse.startY, width, height); |
| 41 | + } |
| 42 | + }; |
| 43 | + |
| 44 | + const handleMouseUp = () => { |
| 45 | + setDraging(false); |
| 46 | + }; |
| 47 | + |
4 | 48 | return ( |
5 | | - <section className="flex flex-1"> |
6 | | - <p>Hello!</p> |
7 | | - </section> |
| 49 | + <canvas |
| 50 | + ref={canvasRef} |
| 51 | + style={{ cursor: draging ? 'crosshair' : 'default' }} |
| 52 | + className="relative w-full h-full" |
| 53 | + onMouseDown={handleMouseDown} |
| 54 | + onMouseMove={handleMouseMove} |
| 55 | + onMouseUp={handleMouseUp} |
| 56 | + /> |
8 | 57 | ); |
9 | 58 | }; |
10 | 59 |
|
|
0 commit comments