|
7 | 7 | <body> |
8 | 8 | <canvas id="draw" width="800" height="800"></canvas> |
9 | 9 | <script> |
| 10 | + const canvas = document.querySelector('#draw'); |
| 11 | + const context = canvas.getContext('2d'); //can also do 3d |
| 12 | + |
| 13 | + //resize canvas width and height (default set above) |
| 14 | + canvas.width = window.innerWidth; |
| 15 | + canvas.height = window.innerHeight; |
| 16 | + context.strokeStyle = '#BADA55'; //color for strokes |
| 17 | + context.lineJoin = 'round'; //rounded corner when the 2 lines meet |
| 18 | + context.lineCap = 'round'; //rounded corner at the end of line |
| 19 | + context.lineWidth = 20; //make line thicker |
| 20 | + context.globalCompositeOperation = 'multiply'; //blend over each other, but will eventually turn black |
| 21 | + |
| 22 | + let isDrawing = false; //flag for drawing |
| 23 | + let lastX = 0; //starting x value |
| 24 | + let lastY = 0; //starting y value |
| 25 | + let hue = 0; |
| 26 | + let direction = true; |
| 27 | + |
| 28 | + function draw(e) { |
| 29 | + if (!isDrawing) { |
| 30 | + return; //stop the function from running when not mouse down |
| 31 | + } |
| 32 | + context.strokeStyle = `hsl(${hue}, 100%, 50%)`; |
| 33 | + context.beginPath(); |
| 34 | + context.moveTo(lastX, lastY); |
| 35 | + context.lineTo(e.offsetX, e.offsetY); |
| 36 | + context.stroke(); |
| 37 | + //set lastX and lastY so it does not always start from (0, 0) |
| 38 | + [lastX, lastY] = [e.offsetX, e.offsetY] //destructuring |
| 39 | + hue++; |
| 40 | + if (hue >= 360) { |
| 41 | + hue = 0; |
| 42 | + } |
| 43 | + if (context.lineWidth > 100 || context.lineWidth <= 1) { |
| 44 | + direction = !direction; //flip the direction |
| 45 | + } |
| 46 | + if (direction) { |
| 47 | + context.lineWidth++; |
| 48 | + } else { |
| 49 | + context.lineWidth--; |
| 50 | + } |
| 51 | + } |
| 52 | + canvas.addEventListener('mousedown', (event) => { |
| 53 | + isDrawing = true; |
| 54 | + //move mouse to the mousedown point so it does not start from (0, 0) |
| 55 | + [lastX, lastY] = [event.offsetX, event.offsetY] |
| 56 | + }); |
| 57 | + canvas.addEventListener('mousemove', draw); |
| 58 | + canvas.addEventListener('mouseup', () => isDrawing = false); |
| 59 | + canvas.addEventListener('mouseout', () => isDrawing = false); //set to false when mouse leaves the window |
| 60 | + |
10 | 61 | </script> |
11 | 62 |
|
12 | 63 | <style> |
|
0 commit comments