|
| 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 | +<script> |
| 10 | + |
| 11 | +const canvas = document.querySelector("#draw"); |
| 12 | +//canvas is like mspaint. |
| 13 | +//You draw on something called the context, not the canvas element itself |
| 14 | +const ctx = canvas.getContext('2d'); |
| 15 | +canvas.width = window.innerWidth; |
| 16 | +canvas.height = window.innerHeight; |
| 17 | +ctx.strokeStyle = "#BADA55"; |
| 18 | +ctx.lineJoin = "round"; |
| 19 | +ctx.lineCap = "round"; |
| 20 | +ctx.lineWidth = 100; |
| 21 | +// ctx.globalCompositeOperation = 'multiply'; //like photoshop blend modes |
| 22 | + |
| 23 | +let isDrawing = false; |
| 24 | +let lastX = 0; |
| 25 | +let lastY = 0; |
| 26 | +let hue = 0; |
| 27 | +let direction = true; |
| 28 | + |
| 29 | + |
| 30 | +function draw(e) { |
| 31 | + if(!isDrawing) return; //don't draw when not mousedown |
| 32 | + console.log(e); |
| 33 | + ctx.beginPath(); |
| 34 | + ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`; |
| 35 | + //start from |
| 36 | + ctx.moveTo(lastX,lastY); |
| 37 | + ctx.lineTo(e.offsetX, e.offsetY); |
| 38 | + ctx.stroke(); |
| 39 | + [lastX, lastY] = [e.offsetX, e.offsetY]; //es6 trick? |
| 40 | + hue++; |
| 41 | + |
| 42 | + if (hue>=360) { |
| 43 | + hue = 0; |
| 44 | + } |
| 45 | + |
| 46 | + if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1) { |
| 47 | + direction = !direction; //flip the direction |
| 48 | + } |
| 49 | + |
| 50 | + if(direction) { |
| 51 | + ctx.lineWidth++; |
| 52 | + } else { |
| 53 | + ctx.lineWidth--; |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | + |
| 58 | + |
| 59 | +canvas.addEventListener('mousedown', (e) => { |
| 60 | + isDrawing = true; //A flag to be tested if ture or false. A common way of doing things |
| 61 | + [lastX, lastY] = [e.offsetX, e.offsetY]; //update mouse position |
| 62 | +}); |
| 63 | + |
| 64 | +canvas.addEventListener('mousemove', draw); |
| 65 | +canvas.addEventListener('mouseup', () => isDrawing = false); |
| 66 | +canvas.addEventListener('mouseout', () => isDrawing = false); //when the mouse leaves the screen |
| 67 | + |
| 68 | +</script> |
| 69 | + |
| 70 | +<style> |
| 71 | + html, body { |
| 72 | + margin:0; |
| 73 | + } |
| 74 | +</style> |
| 75 | + |
| 76 | +</body> |
| 77 | +</html> |
0 commit comments