|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | + <head> |
| 4 | + <meta charset="UTF-8"> |
| 5 | + <title>HTML5 Canvas</title> |
| 6 | + </head> |
| 7 | + <body> |
| 8 | + <canvas id="draw" width="800" height="800"></canvas> |
| 9 | + |
| 10 | + <script> |
| 11 | + const canvas = document.querySelector('#draw'); |
| 12 | + const ctx = canvas.getContext('2d'); |
| 13 | + |
| 14 | + // spread canvas full window |
| 15 | + canvas.width = window.innerWidth; |
| 16 | + canvas.height = window.innerHeight; |
| 17 | + |
| 18 | + // set defaults |
| 19 | + ctx.strokeStyle = '#BADA55'; |
| 20 | + ctx.lineJoin = 'round'; |
| 21 | + ctx.lineCap = 'round'; |
| 22 | + ctx.lineWidth = 100; |
| 23 | + |
| 24 | + let isDrawing = false; |
| 25 | + let lastX = 0; |
| 26 | + let lastY = 0; |
| 27 | + let hue = 0; |
| 28 | + let direction = true; |
| 29 | + |
| 30 | + function draw(e) { |
| 31 | + if (!isDrawing) return; // only draw when mouse is down |
| 32 | + |
| 33 | + console.log(e); |
| 34 | + |
| 35 | + ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`; |
| 36 | + |
| 37 | + ctx.beginPath(); |
| 38 | + ctx.moveTo(lastX, lastY); |
| 39 | + ctx.lineTo(e.offsetX, e.offsetY); |
| 40 | + ctx.stroke(); |
| 41 | + |
| 42 | + [lastX, lastY] = [e.offsetX, e.offsetY]; |
| 43 | + |
| 44 | + if (hue >= 360) { |
| 45 | + hue = 0; |
| 46 | + } else { |
| 47 | + hue++; |
| 48 | + } |
| 49 | + |
| 50 | + if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1) { |
| 51 | + direction = !direction; |
| 52 | + } |
| 53 | + |
| 54 | + if (direction) { |
| 55 | + ctx.lineWidth++; |
| 56 | + } else { |
| 57 | + ctx.lineWidth--; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + canvas.addEventListener('mousedown', (e) => { |
| 62 | + isDrawing = true; |
| 63 | + [lastX, lastY] = [e.offsetX, e.offsetY]; |
| 64 | + }); |
| 65 | + |
| 66 | + canvas.addEventListener('mousemove', draw); |
| 67 | + canvas.addEventListener('mouseup', () => isDrawing = false); |
| 68 | + canvas.addEventListener('mouseout', () => isDrawing = false); |
| 69 | + </script> |
| 70 | + |
| 71 | + <style> |
| 72 | + html, body { |
| 73 | + margin:0; |
| 74 | + } |
| 75 | + </style> |
| 76 | + </body> |
| 77 | +</html> |
0 commit comments