|
7 | 7 | <body>
|
8 | 8 | <canvas id="draw" width="800" height="800"></canvas>
|
9 | 9 | <script>
|
| 10 | + // set up drawing parameters |
| 11 | + var lastX = 0; |
| 12 | + var lastY = 0; |
| 13 | + var isDrawing = false; |
| 14 | + var maxWidth = 50; |
| 15 | + var minWidth = 5; |
| 16 | + var hue = 1; |
| 17 | + var direction = 1; |
| 18 | + |
| 19 | + // set up canvas |
| 20 | + var canvas = document.getElementById('draw'); |
| 21 | + var ctx = canvas.getContext('2d'); |
| 22 | + ctx.canvas.width = window.innerWidth; |
| 23 | + ctx.canvas.height = window.innerHeight; |
| 24 | + ctx.lineWidth = minWidth; |
| 25 | + ctx.strokeStyle = 'red'; |
| 26 | + ctx.lineJoin = 'round'; |
| 27 | + ctx.lineCap = 'round'; |
| 28 | + |
| 29 | + var stopDrawing = function() { |
| 30 | + isDrawing = false; |
| 31 | + } |
| 32 | + |
| 33 | + var startDrawing = function(e) { |
| 34 | + isDrawing = true; |
| 35 | + lastX = e.offsetX; |
| 36 | + lastY = e.offsetY; |
| 37 | + } |
| 38 | + |
| 39 | + var draw = function(e) { |
| 40 | + if (!isDrawing) { |
| 41 | + return; |
| 42 | + } |
| 43 | + // handle the drawing |
| 44 | + ctx.strokeStyle = 'hsl(' + hue.toString() + ', 100%, 50%)'; |
| 45 | + ctx.beginPath(); |
| 46 | + ctx.moveTo(lastX, lastY); |
| 47 | + ctx.lineTo(e.offsetX, e.offsetY); |
| 48 | + ctx.stroke(); |
| 49 | + |
| 50 | + // reset current location |
| 51 | + lastX = e.offsetX; |
| 52 | + lastY = e.offsetY; |
| 53 | + |
| 54 | + // make the line change widths |
| 55 | + if (ctx.lineWidth > maxWidth || ctx.lineWidth < minWidth) { |
| 56 | + direction *= -1; |
| 57 | + } |
| 58 | + ctx.lineWidth += direction; |
| 59 | + |
| 60 | + // draw in rainbow colors |
| 61 | + hue += 0.25; |
| 62 | + hue %= 360; |
| 63 | + } |
| 64 | + |
| 65 | + canvas.addEventListener('mousedown', startDrawing); |
| 66 | + canvas.addEventListener('mousemove', draw); |
| 67 | + canvas.addEventListener('mouseup', stopDrawing); |
| 68 | + canvas.addEventListener('mouseout', stopDrawing); |
10 | 69 | </script>
|
11 | 70 |
|
12 | 71 | <style>
|
|
0 commit comments