|
5 | 5 | <title>HTML5 Canvas</title> |
6 | 6 | </head> |
7 | 7 | <body> |
8 | | -<canvas id="draw" width="800" height="800"></canvas> |
9 | | -<script> |
10 | | -</script> |
| 8 | + <h1>Draw on me!</h1> |
| 9 | + <canvas id="draw" width="800" height="800"></canvas> |
| 10 | + <script> |
11 | 11 |
|
12 | | -<style> |
13 | | - html, body { |
14 | | - margin:0; |
| 12 | + let isDrawing = false; // flag to know when mouse is actually clicked down |
| 13 | + let lastX = 0; |
| 14 | + let lastY = 0; |
| 15 | + let hue = 0; // 0-360, resets after 360 |
| 16 | + let direction = true; |
| 17 | + |
| 18 | + const canvas = document.querySelector('#draw'); |
| 19 | + const ctx = canvas.getContext('2d'); // where we do all drawing |
| 20 | + // resize the canvas |
| 21 | + canvas.width = window.innerWidth; |
| 22 | + canvas.height = window.innerHeight; |
| 23 | + // set paintbrush settings |
| 24 | + ctx.strokeStyle = '#BADA55'; |
| 25 | + ctx.lineJoin = 'round'; |
| 26 | + ctx.lineCap = 'round'; |
| 27 | + ctx.lineWidth = 10; |
| 28 | + // ctx.globalCompositeOperation = 'multiply'; // subtract, lighten etc |
| 29 | + |
| 30 | + function draw(event) { |
| 31 | + if (!isDrawing) { |
| 32 | + return; // don't run when not moused down |
| 33 | + } |
| 34 | + // paint color |
| 35 | + ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`; // hue, saturation, lightness |
| 36 | + |
| 37 | + ctx.beginPath(); |
| 38 | + ctx.moveTo(lastX, lastY); |
| 39 | + ctx.lineTo(event.offsetX, event.offsetY); |
| 40 | + ctx.stroke(); // actually draw |
| 41 | + |
| 42 | + [lastX, lastY] = [event.offsetX, event.offsetY]; |
| 43 | + hue++; |
| 44 | + // increment paint size from 0-100, then back down to 1 |
| 45 | + if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1) { |
| 46 | + direction = !direction; // flip direction |
| 47 | + } |
| 48 | + if (direction) { |
| 49 | + ctx.lineWidth++; |
| 50 | + } else { |
| 51 | + ctx.lineWidth--; |
| 52 | + } |
15 | 53 | } |
16 | | -</style> |
| 54 | + |
| 55 | + canvas.addEventListener('mousedown', (e) => { |
| 56 | + isDrawing = true; |
| 57 | + [lastX, lastY] = [e.offsetX, e.offsetY]; |
| 58 | + }); |
| 59 | + canvas.addEventListener('mouseup', () => isDrawing = false); |
| 60 | + canvas.addEventListener('mouseout', () => isDrawing = false); |
| 61 | + canvas.addEventListener('mousemove', draw); |
| 62 | + |
| 63 | + </script> |
| 64 | + |
| 65 | + <style> |
| 66 | + html, body { |
| 67 | + margin:0; |
| 68 | + } |
| 69 | + </style> |
17 | 70 |
|
18 | 71 | </body> |
19 | 72 | </html> |
0 commit comments