|
| 1 | +class Painter { |
| 2 | + constructor(ctx) { |
| 3 | + ctx.strokeStyle = '#BADA55'; |
| 4 | + ctx.lineJoin = 'round'; |
| 5 | + ctx.lineCap = 'round'; |
| 6 | + this.ctx = ctx; |
| 7 | + |
| 8 | + this.MIN_LINE_WIDTH = 1; |
| 9 | + this.MAX_LINE_WIDTH = 100; |
| 10 | + |
| 11 | + this.isDrawing = false; |
| 12 | + this.lastX = this.lastY = 0; |
| 13 | + this.hue = 0; |
| 14 | + this.direction = true; |
| 15 | + } |
| 16 | + |
| 17 | + draw(e) { |
| 18 | + if (!this.isDrawing) { return; } |
| 19 | + |
| 20 | + const ctx = this.ctx; |
| 21 | + ctx.strokeStyle = `hsl(${this.hue}, 100%, 50%)`; |
| 22 | + ctx.beginPath(); |
| 23 | + ctx.moveTo(this.lastX, this.lastY); |
| 24 | + ctx.lineTo(e.offsetX, e.offsetY); |
| 25 | + ctx.stroke(); |
| 26 | + |
| 27 | + [this.lastX, this.lastY] = [e.offsetX, e.offsetY]; |
| 28 | + this.hue < 360 ? this.hue++ : this.hue = 0; |
| 29 | + |
| 30 | + if (ctx.lineWidth <= this.MIN_LINE_WIDTH || ctx.lineWidth >= this.MAX_LINE_WIDTH) { |
| 31 | + this.direction = !this.direction; |
| 32 | + } |
| 33 | + this.direction ? ctx.lineWidth++ : ctx.lineWidth--; |
| 34 | + } |
| 35 | + |
| 36 | + startDrawing(e) { |
| 37 | + this.isDrawing = true; |
| 38 | + [this.lastX, this.lastY] = [e.offsetX, e.offsetY]; |
| 39 | + } |
| 40 | + |
| 41 | + stopDrawing() { |
| 42 | + this.isDrawing = false; |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +const canvas = document.querySelector('#draw'); |
| 47 | +canvas.width = window.innerWidth; |
| 48 | +canvas.height = window.innerHeight; |
| 49 | +const painter = new Painter(canvas.getContext('2d')); |
| 50 | +[ |
| 51 | + { eventType: 'mousemove', callback: e => painter.draw(e) }, |
| 52 | + { eventType: 'mousedown', callback: e => painter.startDrawing(e) }, |
| 53 | + { eventType: 'mouseup', callback: () => painter.stopDrawing() }, |
| 54 | + { eventType: 'mouseout', callback: () => painter.stopDrawing() } |
| 55 | +].forEach(({eventType, callback}) => canvas.addEventListener(eventType, callback)); |
0 commit comments