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