<canvas width="600" height="400"></canvas>
<script>
var pantalla = document.querySelector('canvas');
var pincel = pantalla.getContext('2d');
pincel.fillStyle = 'grey';
pincel.fillRect(0, 0, 600, 400);
//crear la paleta de colores
pincel.fillStyle = "red";
pincel.fillRect(0,0 ,50,50);
pincel.fillStyle = "green";
pincel.fillRect(50,0 ,50,50);
pincel.fillStyle = "blue";
pincel.fillRect(100,0 ,50,50);
//crear variables globales
var x;
var y;
var color = "blue";
//cambiar color según posición del mouse
function cambiarColor(){
if ((x > 0 && x < 50) && (y < 50 && y > 0)){
color = "red";
}else if ((x > 50 && x < 100) && (y < 50 && y > 0)){
color = "green";
}else if ((x > 100 && x < 150) && (y < 50 && y > 0)){
color = "blue";
}
}
var puedoDibujar = false;
function dibujarCirculo(evento) {
x = evento.pageX - pantalla.offsetLeft;
y = evento.pageY - pantalla.offsetTop;
//no pintar sobre la paleta.
if((x > 0) &&
(x < 150) &&
(y > 0) &&
(y < 50)){
return;
}
if(puedoDibujar) {
pincel.fillStyle = color;
pincel.beginPath();
pincel.arc(x, y, 5, 0, 2 * 3.14);
pincel.fill();
}
}
pantalla.onmousemove = dibujarCirculo;
function habilitarDibujar() {
puedoDibujar = true;
}
function deshabilitarDibujar() {
puedoDibujar = false;
}
pantalla.onmousedown = habilitarDibujar;
pantalla.onmouseup = deshabilitarDibujar;
//agregar para cambiar color al hacer click
pantalla.onclick = cambiarColor;
</script>