11<!DOCTYPE html>
22< html lang ="en ">
3+
34< head >
4- < meta charset ="UTF-8 ">
5- < title > HTML5 Canvas</ title >
5+ < meta charset ="UTF-8 ">
6+ < title > HTML5 Canvas</ title >
67</ head >
8+
79< body >
8- < canvas id ="draw " width ="800 " height ="800 "> </ canvas >
9- < script >
10- </ script >
10+ < canvas id ="draw " width ="800 " height ="800 "> </ canvas >
11+ < script >
12+ const canvas = document . querySelector ( '#draw' ) ;
13+ const ctx = canvas . getContext ( '2d' ) ;
14+ canvas . width = window . innerWidth ;
15+ canvas . height = window . innerHeight ;
16+ ctx . strokeStyle = '#BADA55' ;
17+ ctx . lineJoin = 'round' ;
18+ ctx . lineCap = 'round' ;
19+ ctx . lineWidth = 50 ;
20+
21+ let isDrawing = false ;
22+ let lastX = 0 ;
23+ let lastY = 0 ;
24+ let hue = 0 ;
25+ let direction = true ;
26+
27+ function draw ( e ) {
28+ if ( ! isDrawing ) {
29+ return ;
30+ }
31+
32+ ctx . strokeStyle = `hsl(${ hue } , 100%, 50%)` ;
33+
34+ ctx . beginPath ( ) ;
35+ ctx . moveTo ( lastX , lastY ) ;
36+ ctx . lineTo ( e . offsetX , e . offsetY ) ;
37+ ctx . stroke ( ) ;
38+ [ lastX , lastY ] = [ e . offsetX , e . offsetY ] ;
39+ hue ++ ;
40+
41+ if ( hue >= 360 ) {
42+ hue = 0 ;
43+ }
1144
12- < style >
13- html , body {
14- margin : 0 ;
15- }
16- </ style >
45+ if ( ctx . lineWidth >= 100 || ctx . lineWidth <= 1 ) {
46+ direction = ! direction ;
47+ }
48+
49+ if ( direction ) {
50+ ctx . lineWidth ++ ;
51+ } else {
52+ ctx . lineWidth -- ;
53+ }
54+ }
55+
56+ canvas . addEventListener ( 'mousedown' , ( e ) => {
57+ isDrawing = true ;
58+ [ lastX , lastY ] = [ e . offsetX , e . offsetY ] ;
59+
60+
61+ } ) ;
62+ canvas . addEventListener ( 'mousemove' , draw ) ;
63+ canvas . addEventListener ( 'mouseup' , ( ) => isDrawing = false ) ;
64+ canvas . addEventListener ( 'mouseout ' , ( ) => isDrawing = false ) ;
65+ </ script >
66+
67+ < style >
68+ html ,
69+ body {
70+ margin : 0 ;
71+ }
72+ </ style >
1773
1874</ body >
19- </ html >
75+
76+ </ html >
0 commit comments