File tree Expand file tree Collapse file tree
08 - Fun with HTML5 Canvas Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11<!DOCTYPE html>
22< html lang ="en ">
3+
34< head >
45 < meta charset ="UTF-8 ">
56 < 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+
15+ canvas . width = window . innerWidth
16+ canvas . height = window . innerHeight
17+
18+ ctx . strokeStyle = '#BADA55'
19+ ctx . lineJoin = 'round'
20+ ctx . lineCap = 'round'
21+
22+ let isDrawing = false
23+ let lastX = 0
24+ let lastY = 0
1125
12- < style >
13- html , body {
14- margin : 0 ;
15- }
16- </ style >
26+ function draw ( e ) {
27+ if ( ! isDrawing ) return // get out of this function if we aren't in drawing mode.
28+ console . log ( e ) ;
29+ ctx . beginPath ( ) ;
30+ ctx . moveTo ( lastX , lastY ) ;
31+ ctx . lineTo ( e . offsetX , e . offsetY ) ;
32+ ctx . stroke ( ) ;
33+ [ lastX , lastY ] = [ e . offsetX , e . offsetY ] ;
34+ }
35+
36+ canvas . addEventListener ( 'mousedown' , ( e ) => {
37+ isDrawing = true ;
38+ [ lastX , lastY ] = [ e . offsetX , e . offsetY ] ;
39+ } )
40+
41+ canvas . addEventListener ( 'mousemove' , draw ) ;
42+ canvas . addEventListener ( 'mouseup' , ( ) => isDrawing = false ) ;
43+ canvas . addEventListener ( 'mouseout' , ( ) => isDrawing = false ) ;
44+ </ script >
45+
46+ < style >
47+ html ,
48+ body {
49+ margin : 0 ;
50+ }
51+ </ style >
1752
1853</ body >
19- </ html >
54+
55+ </ html >
You can’t perform that action at this time.
0 commit comments