|
| 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 | + const canvas = document.querySelector('#draw'); |
| 11 | + const ctx = canvas.getContext('2d'); |
| 12 | + |
| 13 | + canvas.width = window.innerWidth; |
| 14 | + canvas.height = window.innerHeight; |
| 15 | + |
| 16 | + ctx.strokeStyle = '#ff00ff'; |
| 17 | + ctx.lineJoin = 'round'; |
| 18 | + ctx.lineCap = 'round'; |
| 19 | + ctx.lineWidth = 50; |
| 20 | + |
| 21 | + let isDrawing = false; |
| 22 | + let lastX, lastY, lastWidth; |
| 23 | + let hue = 0; |
| 24 | + |
| 25 | + function draw(e) { |
| 26 | + if (!isDrawing) { |
| 27 | + return; |
| 28 | + } |
| 29 | + // calculate width based on drawing speed |
| 30 | + const dist = Math.sqrt(Math.pow(lastX - e.offsetX, 2) + Math.pow(lastY - e.offsetY, 2)); |
| 31 | + let width = Math.pow(dist, 1.2); |
| 32 | + width = Math.max(width, 5); |
| 33 | + width = Math.min(width, 100); |
| 34 | + if (lastWidth) { |
| 35 | + // limit width growth |
| 36 | + width = lastWidth + Math.max(Math.min(width - lastWidth, 1), -1); |
| 37 | + } |
| 38 | + ctx.lineWidth = width; |
| 39 | + ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`; |
| 40 | + ctx.beginPath(); |
| 41 | + ctx.moveTo(lastX, lastY); |
| 42 | + ctx.lineTo(e.offsetX, e.offsetY); |
| 43 | + ctx.stroke(); |
| 44 | + lastX = e.offsetX; |
| 45 | + lastY = e.offsetY; |
| 46 | + lastWidth = width; |
| 47 | + hue++; |
| 48 | + hue = hue >= 360 ? 0 : hue; |
| 49 | + } |
| 50 | + |
| 51 | + canvas.addEventListener('mousemove', draw); |
| 52 | + canvas.addEventListener('mousedown', (e) => { |
| 53 | + isDrawing = true; |
| 54 | + lastX = e.offsetX; |
| 55 | + lastY = e.offsetY; |
| 56 | + lastWidth = null; |
| 57 | + }); |
| 58 | + canvas.addEventListener('mouseout', () => isDrawing = false); |
| 59 | + canvas.addEventListener('mouseup', () => isDrawing = false); |
| 60 | +</script> |
| 61 | + |
| 62 | +<style> |
| 63 | + html, body { |
| 64 | + margin:0; |
| 65 | + } |
| 66 | +</style> |
| 67 | + |
| 68 | +</body> |
| 69 | +</html> |
0 commit comments