Acá les dejo mi código, espero les pueda servir como un punto de vista diferente de la solución al proyecto propuesto... Saludos!!!
<canvas width="600" height="400"></canvas>
<script>
const d = document
var $canvas = d.querySelector("canvas")
var brush = $canvas.getContext("2d")
let canvasW = $canvas.getAttribute("width")
let canvasH = $canvas.getAttribute("height")
brush.fillStyle = "lightgray"
brush.fillRect(0, 0, canvasW, canvasH)
function drawCircle(e, radius, canIDraw, fill) {
let fullAngle = 2 * Math.PI
if(canIDraw) {
let xClick = e.offsetX
let yClick = e.offsetY
// Dibujar sólo fuera de la paleta de colores
if(xClick > width * colorsArr.length || yClick > height) {
brush.fillStyle = fill
brush.beginPath()
brush.arc(xClick, yClick, radius, 0, fullAngle)
brush.fill()
}
}
}
function drawColorPicker(color, x, y, width, height) {
brush.fillStyle = color
brush.fillRect(x, y, width, height)
}
function drawColorPalette(colors, x, y, width, height) {
for(i = 0; i < colors.length; i++) {
drawColorPicker(colors[i], x, y, width, height)
x += width
}
}
canIDraw = false
let fill = "blue"
let radius = 3
let x = 0
let y = 0
let width = 50
let height = width
const colorsArr = ["red", "green", "blue"]
drawColorPalette(colorsArr, x, y, width, height)
$canvas.addEventListener("mousemove", (e) => {
drawCircle(e, radius, canIDraw, fill)
})
$canvas.addEventListener("mousedown", (e) => {
if(e) canIDraw = true
})
$canvas.addEventListener("mouseup", (e) => {
if(e) canIDraw = false
})
$canvas.addEventListener("click", (e) => {
let xClick = e.offsetX
let yClick = e.offsetY
if(yClick <= height) {
if(xClick <= 50) fill = colorsArr[0]
if(xClick > 50 && xClick <= 100) fill = colorsArr[1]
if(xClick > 100 && xClick <= 150) fill = colorsArr[2]
}
})
</script>