2
respuestas

Diseño con mouse y extras

ejercicio final

2 respuestas
//Creando un mini paint con 3 colores

//Variables

let pantalla = document.querySelector('.canvas');
let pincel = pantalla.getContext('2d');
let borrador = document.querySelector('.clean');
let puedoDibujar = false;
const colores = ['red', 'green', 'blue'];
let color = colores[2];
let x;
let y;

//Funciones
function cuadradoRojo() {
    pincel.fillStyle = colores[0];
    pincel.fillRect(0, 0, 50, 50);
}
function cuadradoVerde() {
    pincel.fillStyle = colores[1];
    pincel.fillRect(50, 0, 50, 50);
}
function cuadradoAzul() {
    pincel.fillStyle = colores[2];
    pincel.fillRect(100, 0, 50, 50);
}

cuadradoRojo();
cuadradoVerde();
cuadradoAzul();

function cambioColor(e) {
    x = e.pageX - pantalla.offsetLeft;
    y = e.pageY - pantalla.offsetTop;

    if (x > 0 && x < 50 && y < 50) {
        color = colores[0];
    }
    if (x > 50 && x < 100 && y < 50) {
        color = colores[1];
    }
    if (x > 100 && x < 150 && y < 50) {
        color = colores[2];
    }
}

//Creando la función para limpiar el circulo dibujado
function limpiar() {
    pincel.clearRect(0, 0, 1200, 600);
    cuadradoRojo();
    cuadradoVerde();
    cuadradoAzul();
}

function dibujarCirculo(e) {
    //If para conocer y obtener las coordenadas de los ejes "x" y "y"
    if (puedoDibujar) {
        x = e.pageX - pantalla.offsetLeft;
        y = e.pageY - pantalla.offsetTop;

        if (y > 50 || x > 150) {
            pincel.fillStyle = color;
            pincel.beginPath();
            pincel.arc(x, y, 5, 0, 2 * Math.PI);
            pincel.fill();
        }
    }
}

pantalla.onmousemove = dibujarCirculo;

function habilitarDibujar(e) {
    puedoDibujar = true;
    cambioColor(e);
}

function deshabilitarDibujar() {
    puedoDibujar = false;
}

borrador.onclick = limpiar;
//Cuando se tenga el boton presionado se activara esta función
pantalla.onmousedown = habilitarDibujar;
//Cuando no este el boton presionado se activara esta función
pantalla.onmouseup = deshabilitarDibujar;

Hola Jesus

Gracias por compartir tu código, está muy bien felicitaciones.

Si tienes alguna pregunta sobre el contenido de los cursos, estaremos aquí para ayudarte.

Si este post te ayudó, por favor, marca como solucionado ✓. Continúa con tus estudios