11import React , { MouseEvent , useRef , useState } from 'react' ;
22
33const Screen = ( ) => {
4+ const parentRef = useRef < HTMLDivElement > ( null ) ;
45 const canvasRef = useRef < HTMLCanvasElement > ( null ) ;
56
67 const [ mouse , setMouse ] = useState ( {
78 startX : 0 ,
89 startY : 0 ,
910 } ) ;
10- const [ draging , setDraging ] = useState ( true ) ;
11+ const [ draging , setDraging ] = useState ( false ) ;
1112
1213 const handleMouseDown = ( ev : MouseEvent ) => {
1314 setMouse ( {
1415 startX : ev . pageX - ( canvasRef . current ?. getBoundingClientRect ( ) . left || 0 ) ,
1516 startY : ev . pageY - ( canvasRef . current ?. getBoundingClientRect ( ) . top || 0 ) ,
1617 } ) ;
18+ const ctx = canvasRef . current ;
19+ if ( ctx ) {
20+ ctx . width = window . innerWidth || 1000 ;
21+ ctx . height = window . innerHeight || 1000 ;
22+ }
1723
1824 setDraging ( true ) ;
1925 } ;
@@ -35,7 +41,12 @@ const Screen = () => {
3541 ( canvasRef . current ?. getBoundingClientRect ( ) . top || 0 ) -
3642 mouse . startY ;
3743
38- ctx . clearRect ( 0 , 0 , 1000 , 1000 ) ;
44+ ctx . clearRect (
45+ 0 ,
46+ 0 ,
47+ parentRef . current ?. clientWidth || 1000 ,
48+ parentRef . current ?. clientHeight || 1000
49+ ) ;
3950 ctx . fillStyle = 'red' ;
4051 ctx . fillRect ( mouse . startX , mouse . startY , width , height ) ;
4152 }
@@ -46,14 +57,18 @@ const Screen = () => {
4657 } ;
4758
4859 return (
49- < canvas
50- ref = { canvasRef }
60+ < div
5161 style = { { cursor : draging ? 'crosshair' : 'default' } }
52- className = "relative w-full h-full"
53- onMouseDown = { handleMouseDown }
54- onMouseMove = { handleMouseMove }
55- onMouseUp = { handleMouseUp }
56- />
62+ className = "w-full h-full"
63+ ref = { parentRef }
64+ >
65+ < canvas
66+ ref = { canvasRef }
67+ onMouseDown = { handleMouseDown }
68+ onMouseMove = { handleMouseMove }
69+ onMouseUp = { handleMouseUp }
70+ />
71+ </ div >
5772 ) ;
5873} ;
5974
0 commit comments