From 9e1a6b39674267b8489f2158b61a368976d35f85 Mon Sep 17 00:00:00 2001 From: Rob Richardson Date: Tue, 9 Jul 2024 18:43:28 -0600 Subject: [PATCH] Sometimes the user draws a bit with the new color before the color picker change event fires --- drawing-app/script.js | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/drawing-app/script.js b/drawing-app/script.js index 833a43f..946b0d2 100644 --- a/drawing-app/script.js +++ b/drawing-app/script.js @@ -14,11 +14,17 @@ let color = colorEl.value let x let y +let startColor +let points = [] + canvas.addEventListener('mousedown', (e) => { isPressed = true x = e.offsetX y = e.offsetY + + startColor = color + points.push({x, y}) }) document.addEventListener('mouseup', (e) => { @@ -26,6 +32,8 @@ document.addEventListener('mouseup', (e) => { x = undefined y = undefined + startColor = undefined + points = [] }) canvas.addEventListener('mousemove', (e) => { @@ -33,6 +41,10 @@ canvas.addEventListener('mousemove', (e) => { const x2 = e.offsetX const y2 = e.offsetY + if (startColor) { + points.push({x: x2, y: y2}) + } + drawCircle(x2, y2) drawLine(x, y, x2, y2) @@ -42,6 +54,7 @@ canvas.addEventListener('mousemove', (e) => { }) function drawCircle(x, y) { + console.log('circle', x, y, color) ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2) ctx.fillStyle = color @@ -49,6 +62,7 @@ function drawCircle(x, y) { } function drawLine(x1, y1, x2, y2) { + console.log('line', x1, y1, x2, y2, color) ctx.beginPath() ctx.moveTo(x1, y1) ctx.lineTo(x2, y2) @@ -81,6 +95,23 @@ decreaseBtn.addEventListener('click', () => { updateSizeOnScreen() }) -colorEl.addEventListener('change', (e) => color = e.target.value) +colorEl.addEventListener('change', (e) => { + color = e.target.value + + if (isPressed) { + console.log('color changed while drawing') + if (startColor !== color) { + console.log(`fixing ${points.length} dots from ${startColor} to ${color}`) + for (let i = 0; i < points.length - 1; i++) { + drawCircle(points[i].x, points[i].y) + drawLine(points[i].x, points[i].y, points[i + 1].x, points[i + 1].y) + drawCircle(points[i + 1].x, points[i + 1].y) + } + console.log('done fixing it') + startColor = color + points = [] + } + } +}) clearEl.addEventListener('click', () => ctx.clearRect(0,0, canvas.width, canvas.height))