File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
08 - Fun with HTML5 Canvas Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 77< body >
88< canvas id ="draw " width ="800 " height ="800 "> </ canvas >
99< script >
10+ const canvas = document . querySelector ( '#draw' ) ;
11+ const ctx = canvas . getContext ( '2d' ) ;
12+ canvas . width = window . innerWidth ;
13+ canvas . height = window . innerHeight ;
14+ ctx . strokeStyle = '#000000' ;
15+ ctx . lineJoin = 'round' ;
16+ ctx . lineCap = 'round' ;
17+ ctx . lineWidth = 100 ;
18+
19+ let isDrawing = false ;
20+ let lastX = 0 ;
21+ let lastY = 0 ;
22+ let hue = 0 ;
23+ let direction = true ;
24+
25+ function draw ( e ) {
26+ if ( ! isDrawing ) return ; //Stops function if user not moused down
27+ console . log ( e ) ;
28+ ctx . strokeStyle = `hsl(${ hue } , 100%, 50%)` ;
29+ ctx . beginPath ( ) ;
30+ //start line from
31+ ctx . moveTo ( lastX , lastY ) ;
32+ //move line to
33+ ctx . lineTo ( e . offsetX , e . offsetY ) ;
34+ ctx . stroke ( ) ;
35+ lastX = e . offsetX ;
36+ lastY = e . offsetY ;
37+
38+ hue ++ ;
39+ if ( hue >= 360 ) {
40+ hue = 0 ;
41+ }
42+
43+ if ( ctx . lineWidth >= 100 || ctx . lineWidth <= 1 ) {
44+ direction = ! direction ;
45+ }
46+
47+ if ( direction ) {
48+ ctx . lineWidth ++ ;
49+ } else {
50+ ctx . lineWidth -- ;
51+ }
52+
53+ }
54+
55+ canvas . addEventListener ( 'mousedown' , ( e ) => {
56+ isDrawing = true ;
57+ lastX = e . offsetX ;
58+ lastY = e . offsetY ;
59+ } ) ;
60+
61+ canvas . addEventListener ( 'mousemove' , draw ) ;
62+ canvas . addEventListener ( 'mouseup' , ( ) => isDrawing = false ) ;
63+ canvas . addEventListener ( 'mouseout' , ( ) => isDrawing = false ) ;
1064</ script >
1165
1266< style >
You can’t perform that action at this time.
0 commit comments