diff options
Diffstat (limited to 'draw/app.js')
| -rw-r--r-- | draw/app.js | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/draw/app.js b/draw/app.js new file mode 100644 index 0000000..d8b6ebf --- /dev/null +++ b/draw/app.js | |||
| @@ -0,0 +1,66 @@ | |||
| 1 | let paintStyle = getComputedStyle(document.querySelector('section')); | ||
| 2 | let canvas = document.querySelector('canvas'); | ||
| 3 | let ctx = canvas.getContext('2d'); | ||
| 4 | |||
| 5 | canvas.width = parseInt(paintStyle.getPropertyValue('width')); | ||
| 6 | canvas.height = parseInt(paintStyle.getPropertyValue('height')); | ||
| 7 | |||
| 8 | var mouse = { | ||
| 9 | x: 0, | ||
| 10 | y: 0 | ||
| 11 | }; | ||
| 12 | |||
| 13 | ctx.lineWidth = 3; | ||
| 14 | ctx.lineJoin = 'round'; | ||
| 15 | ctx.lineCap = 'round'; | ||
| 16 | ctx.strokeStyle = 'limegreen'; | ||
| 17 | |||
| 18 | canvas.addEventListener('mousemove', function(e) { | ||
| 19 | mouse.x = e.pageX - this.offsetLeft; | ||
| 20 | mouse.y = e.pageY - this.offsetTop; | ||
| 21 | }, false); | ||
| 22 | |||
| 23 | canvas.addEventListener('mousedown', function(e) { | ||
| 24 | ctx.beginPath(); | ||
| 25 | ctx.moveTo(mouse.x, mouse.y); | ||
| 26 | canvas.addEventListener('mousemove', onPaint, false); | ||
| 27 | }, false); | ||
| 28 | |||
| 29 | canvas.addEventListener('mouseup', function() { | ||
| 30 | canvas.removeEventListener('mousemove', onPaint, false); | ||
| 31 | }, false); | ||
| 32 | |||
| 33 | var onPaint = function() { | ||
| 34 | ctx.lineCap = 'round'; | ||
| 35 | ctx.lineTo(mouse.x, mouse.y); | ||
| 36 | ctx.stroke(); | ||
| 37 | }; | ||
| 38 | |||
| 39 | |||
| 40 | document.querySelectorAll('nav button').forEach(function(button, idx) { | ||
| 41 | button.addEventListener('click', function(evt) { | ||
| 42 | console.log(button.dataset.method); | ||
| 43 | |||
| 44 | switch (button.dataset.method) { | ||
| 45 | case 'color': | ||
| 46 | { | ||
| 47 | ctx.strokeStyle = button.dataset.value; | ||
| 48 | break; | ||
| 49 | } | ||
| 50 | case 'size': | ||
| 51 | { | ||
| 52 | ctx.lineWidth = parseInt(button.dataset.value); | ||
| 53 | break; | ||
| 54 | } | ||
| 55 | case 'clear': | ||
| 56 | { | ||
| 57 | let clear = confirm('Do you really want to clear canvas?'); | ||
| 58 | if (clear) { | ||
| 59 | ctx.clearRect(0, 0, canvas.width, canvas.height); | ||
| 60 | } | ||
| 61 | break; | ||
| 62 | } | ||
| 63 | } | ||
| 64 | }); | ||
| 65 | |||
| 66 | }); | ||
