File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
08 - Fun with HTML5 Canvas Expand file tree Collapse file tree 1 file changed +50
-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+
13+ canvas . width = window . innerWidth ;
14+ canvas . height = window . innerHeight ;
15+
16+ ctx . strokeStyle = '#BADA55' ;
17+ ctx . lineJoin = 'round' ;
18+ ctx . lineCap = 'round' ;
19+ ctx . lineWidth = 1 ;
20+ // ctx.globalCompositeOperation = 'multiply';
21+
22+ let isDrawing = false ;
23+ let lastX = 0 ;
24+ let lastY = 0 ;
25+ let hue = 0 ;
26+ let direction = true ;
27+
28+ function draw ( e ) {
29+ if ( ! isDrawing ) return ; // stop the function from running when they are not mouse down
30+ // console.log(e);
31+ ctx . strokeStyle = `hsl(${ hue } , 100%, 50%)` ;
32+ ctx . beginPath ( ) ;
33+ ctx . moveTo ( lastX , lastY ) ;
34+ ctx . lineTo ( e . offsetX , e . offsetY ) ;
35+ ctx . stroke ( ) ;
36+ [ lastX , lastY ] = [ e . offsetX , e . offsetY ] ;
37+ hue ++ ;
38+ if ( hue >= 360 ) {
39+ hue = 0 ;
40+ }
41+
42+ if ( ctx . lineWidth >= 100 || ctx . lineWidth <= 1 ) {
43+ direction = ! direction ;
44+ }
45+
46+ if ( direction ) {
47+ ctx . lineWidth ++ ;
48+ } else {
49+ ctx . lineWidth -- ;
50+ }
51+ }
52+
53+ canvas . addEventListener ( 'mousedown' , ( e ) => {
54+ isDrawing = true ;
55+ [ lastX , lastY ] = [ e . offsetX , e . offsetY ] ;
56+ } ) ;
57+ canvas . addEventListener ( 'mousemove' , draw ) ;
58+ canvas . addEventListener ( 'mouseup' , ( ) => isDrawing = false ) ;
59+ canvas . addEventListener ( 'mouseout' , ( ) => isDrawing = false ) ;
1060</ script >
1161
1262< style >
You can’t perform that action at this time.
0 commit comments