File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
08 - Fun with HTML5 Canvas Expand file tree Collapse file tree 1 file changed +52
-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 = '#BADA55'
15+ ctx . lineJoin = 'round'
16+ ctx . lineCap = 'round'
17+ ctx . lineWidth = 30
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 ; // Stop the fn from running when they are not moused down
27+ console . log ( e )
28+ ctx . strokeStyle = `hsl(${ hue } , 100%, 50%)`
29+ ctx . beginPath ( )
30+ // start from
31+ ctx . moveTo ( lastX , lastY )
32+ // go to
33+ ctx . lineTo ( e . offsetX , e . offsetY )
34+ ctx . stroke ( )
35+ lastX = e . offsetX
36+ lastY = e . offsetY
37+ hue ++
38+ if ( hue >= 360 ) {
39+ hue = 0
40+ }
41+ if ( ctx . lineWidth >= 100 || ctx . lineWidth <= 1 ) {
42+ direction = ! direction
43+ }
44+ if ( direction ) {
45+ ctx . lineWidth ++
46+ } else {
47+ ctx . lineWidth --
48+ }
49+ }
50+
51+ canvas . addEventListener ( 'mousedown' , ( e ) => {
52+ isDrawing = true
53+ lastX = e . offsetX
54+ lastY = e . offsetY
55+ } )
56+
57+ canvas . addEventListener ( 'mousemove' , draw )
58+ canvas . addEventListener ( 'mouseup' , ( ) => isDrawing = false )
59+ canvas . addEventListener ( 'mouseout' , ( ) => isDrawing = false )
60+
61+
1062</ script >
1163
1264< style >
You can’t perform that action at this time.
0 commit comments