1+ <!DOCTYPE html>
2+ < html lang ="en ">
3+ < head >
4+ < meta charset ="UTF-8 ">
5+ < meta name ="viewport " content ="width=device-width, initial-scale=1.0 ">
6+ < title > Canvas</ title >
7+ </ head >
8+ < body >
9+ < canvas id ='canvas '> </ canvas >
10+ < script >
11+ let isDraw = false
12+ let lastMousePosition = { x : 0 , y : 0 }
13+ const canvas = document . getElementById ( 'canvas' )
14+ const ctx = canvas . getContext ( '2d' )
15+
16+ // resize canvas
17+ function resizeCanvas ( ) {
18+ canvas . width = window . innerWidth
19+ canvas . height = window . innerHeight
20+ }
21+ window . addEventListener ( 'resize' , resizeCanvas )
22+ resizeCanvas ( )
23+
24+ // line color
25+ let hue = 0
26+ function updateColor ( ) {
27+ hue = hue + 3
28+ color = `hsl(${ hue } ,100%,70%)`
29+ ctx . globalAlpha = 0.3 ;
30+ ctx . fillStyle = color
31+ }
32+
33+ // line size
34+ let size = 20
35+ let sizeSpeed = 1
36+ function updateSize ( ) {
37+ if ( size < 20 ) sizeSpeed = 0.25
38+ if ( size > 40 ) sizeSpeed = - 0.25
39+ size = size + sizeSpeed
40+ }
41+
42+ function getDots ( from , to , gap ) {
43+ const dx = to . x - from . x
44+ const dy = to . y - from . y
45+ const d = Math . sqrt ( dx * dx + dy * dy )
46+
47+ // number of dots
48+ const n = Math . floor ( d / gap )
49+ if ( n > 100 ) {
50+ n = 100
51+ }
52+ const a = [ {
53+ x : from . x ,
54+ y : from . y
55+ } ]
56+
57+ for ( let i = 1 ; i < n ; i ++ ) {
58+ a . push ( {
59+ x : from . x + i / n * dx ,
60+ y : from . y + i / n * dy
61+ } )
62+ }
63+ return a
64+ }
65+
66+ // draw a circle at x, y
67+ function drawCircle ( x , y , radius ) {
68+ ctx . beginPath ( )
69+ ctx . arc ( x , y , radius , 0 , 2 * Math . PI , false )
70+ ctx . fill ( )
71+ }
72+
73+ // draw a line with dots
74+ function drawLine ( from , to , size ) {
75+ const r = size
76+ const dots = getDots ( from , to , size / 2 )
77+ dots . forEach ( dot => drawCircle ( dot . x , dot . y , r ) )
78+ }
79+
80+ canvas . addEventListener ( "mousedown" , ( e ) => {
81+ isDraw = true
82+ lastMousePosition = {
83+ x : e . offsetX ,
84+ y : e . offsetY
85+ }
86+ } )
87+
88+ canvas . addEventListener ( "mouseup" , ( e ) => {
89+ isDraw = false
90+ } )
91+
92+ canvas . addEventListener ( "mousemove" , ( e ) => {
93+ const currentMousePosition = {
94+ x : e . offsetX ,
95+ y : e . offsetY
96+ }
97+ if ( isDraw ) {
98+ updateColor ( )
99+ updateSize ( )
100+ drawLine ( lastMousePosition , currentMousePosition , size )
101+ }
102+ lastMousePosition = currentMousePosition
103+ } )
104+ </ script >
105+ </ body >
106+ </ html >
0 commit comments