<!DOCTYPE html>
<html lang="es-CO">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Diseñando con el mouse </title>
<meta name="description" content="Permite dibujar lineas con clic sostenido del mouse y cambiar el color de la linea a dibujar." />
</head>
<body>
<canvas width="600" height="400"></canvas>
<script>
let screen = document.querySelector('canvas');
let pincel = screen.getContext('2d');
let xClick;
let YClick;
let color = 'blue';
const colors = ['red', 'green', 'blue'];
pincel.fillStyle = 'grey';
pincel.fillRect(0, 0, 600, 400);
let canDraw = false;
function drawCircle(event) {
xClick = event.pageX - screen.offsetLeft;
yClick = event.pageY - screen.offsetTop;
if(canDraw && validArea() ) {
pincel.fillStyle = color;
pincel.beginPath();
pincel.arc(xClick, yClick, 5, 0, 2 * 3.14);
pincel.fill();
}
}
function validArea(){ //evitamos dibujar sobre las opciones de colores
return (xClick > 155 || yClick > 55) ? true : false;
}
function drawColorSquares(){
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);
}
drawColorSquares();
function evaluateColorChange() {
if( xClick <= 50 && yClick <= 50 ){
color = colors[0];
}else if( xClick <= 100 && yClick <= 50 ){
color = colors[1];
}else if( xClick <= 150 && yClick <= 50 ){
color = colors[2];
}
}
screen.onmousemove = drawCircle;
function enableDraw() {
canDraw = true;
}
function desabledDraw() {
canDraw = false;
}
screen.onmousedown = enableDraw;
screen.onmouseup = desabledDraw;
screen.onclick = evaluateColorChange;
</script>
</body>
</html>