martes, 8 de septiembre de 2026

Mini Paint

La más emocionada que me preguntaron como hice mi mini Paint, dejo el código primero y luego la explicación.


<!-- =====================================================

     GEMA'S PIXEL PAINT

     PARTE 1/4

     Diseño compacto para SIDEBAR DERECHO — 355px

     ===================================================== -->


<div id="gema-pixel-paint">


<style>

/* =====================================================

   BASE

   ===================================================== */


#gema-pixel-paint{

  width:345px;

  max-width:100%;

  margin:12px auto;

  box-sizing:border-box;


  font-family:"Courier New",monospace;

  color:#6b5878;

}


#gema-pixel-paint *,

#gema-pixel-paint *::before,

#gema-pixel-paint *::after{

  box-sizing:border-box;

}


/* =====================================================

   VENTANA

   ===================================================== */


#gpp-window{

  width:345px;

  max-width:100%;


  background:#fffaf8;


  border:3px solid #c96f91;

  border-radius:10px;


  box-shadow:

    5px 5px 0 #9ccfca;


  overflow:hidden;

}


/* =====================================================

   CABECERA

   ===================================================== */


#gpp-header{

  height:39px;


  display:flex;

  align-items:center;

  justify-content:space-between;


  padding:5px 7px 5px 10px;


  background:#dff8ef;


  border-bottom:3px solid #c96f91;

}


#gpp-name{

  display:flex;

  align-items:center;

  gap:6px;


  min-width:0;


  font-size:12px;

  font-weight:bold;


  color:#b85e80;


  white-space:nowrap;

}


#gpp-name-heart{

  font-size:17px;

  color:#c96f91;

}


#gpp-window-buttons{

  display:flex;

  gap:4px;

  flex-shrink:0;

}


.gpp-window-btn{

  width:16px;

  height:16px;


  padding:0;


  border:2px solid #c96f91;

  border-radius:50%;


  background:#ffd979;


  cursor:pointer;

}


.gpp-window-btn:nth-child(2){

  background:#9bdc79;

}


.gpp-window-btn:nth-child(3){

  background:#ed8fb0;

}


/* =====================================================

   MINI MENÚ

   ===================================================== */


#gpp-menu{

  height:27px;


  display:flex;

  align-items:center;

  justify-content:space-around;


  padding:0 6px;


  background:#fffdfc;


  border-bottom:2px solid #efb6c9;


  color:#80617b;


  font-size:8px;

  font-weight:bold;

}


#gpp-menu span{

  cursor:default;

}


/* =====================================================

   ZONA PRINCIPAL

   ===================================================== */


#gpp-main{

  display:grid;


  /*

     Herramientas compactas

     + lienzo grande

  */


  grid-template-columns:72px minmax(0,1fr);


  min-height:236px;


  background:#fffaf8;

}


/* =====================================================

   HERRAMIENTAS

   ===================================================== */


#gpp-tools{

  padding:7px 5px;


  background:#f5fdf9;


  border-right:3px solid #c96f91;


  display:grid;


  grid-template-columns:1fr 1fr;


  gap:5px;


  align-content:start;

}


/* =====================================================

   BOTONES DE HERRAMIENTA

   ===================================================== */


.gpp-tool{

  width:29px;

  height:42px;


  margin:auto;


  padding:2px;


  display:flex;

  flex-direction:column;

  align-items:center;

  justify-content:center;


  gap:2px;


  border:2px solid #d17b99;

  border-radius:4px;


  background:#fff;


  color:#775d78;


  cursor:pointer;


  font-family:"Courier New",monospace;

}


.gpp-tool:hover{

  background:#ffe8ef;

}


.gpp-tool.active{

  background:#dff8ef;


  box-shadow:

    inset 0 0 0 2px #fff,

    2px 2px 0 #9ccfca;

}


.gpp-tool-label{

  font-size:5px;

  line-height:5px;

  font-weight:bold;


  white-space:nowrap;

}


/* =====================================================

   ICONOS PIXEL

   ===================================================== */


.gpp-icon{

  width:20px;

  height:20px;


  position:relative;


  display:block;

}


/* LÁPIZ */


.gpp-pencil::before{

  content:"";


  position:absolute;


  width:6px;

  height:17px;


  left:7px;

  top:1px;


  background:#e7a2bd;


  border:2px solid #776080;


  transform:rotate(43deg);

}


.gpp-pencil::after{

  content:"";


  position:absolute;


  width:0;

  height:0;


  left:4px;

  top:14px;


  border-left:3px solid transparent;

  border-right:3px solid transparent;

  border-top:6px solid #776080;


  transform:rotate(43deg);

}


/* LÁPIZ GRUESO */


.gpp-pencil-big::before{

  content:"";


  position:absolute;


  width:9px;

  height:18px;


  left:6px;

  top:0;


  background:#7cbfc1;


  border:2px solid #776080;


  transform:rotate(43deg);

}


/* BORRADOR */


.gpp-eraser::before{

  content:"";


  position:absolute;


  width:18px;

  height:9px;


  left:1px;

  top:6px;


  background:#e9a2b9;


  border:2px solid #776080;


  transform:rotate(-43deg);

}


.gpp-eraser::after{

  content:"";


  position:absolute;


  width:6px;

  height:9px;


  left:12px;

  top:2px;


  background:#fff;


  border:2px solid #776080;


  transform:rotate(-43deg);

}


/* PINCEL */


.gpp-brush::before{

  content:"";


  position:absolute;


  width:15px;

  height:6px;


  left:1px;

  top:5px;


  background:#f5c66d;


  border:2px solid #776080;


  transform:rotate(-40deg);

}


.gpp-brush::after{

  content:"";


  position:absolute;


  width:7px;

  height:9px;


  right:0;

  bottom:1px;


  background:#d881a2;


  border:2px solid #776080;


  transform:rotate(-40deg);

}


/* RELLENO */


.gpp-fill::before{

  content:"";


  position:absolute;


  width:15px;

  height:15px;


  left:2px;

  top:2px;


  background:#b8ef8d;


  border:2px solid #776080;


  transform:rotate(45deg);

}


.gpp-fill::after{

  content:"";


  position:absolute;


  width:7px;

  height:4px;


  right:0;

  bottom:2px;


  background:#7cbfc1;

}


/* GOTERO */


.gpp-dropper::before{

  content:"";


  position:absolute;


  width:6px;

  height:17px;


  left:7px;

  top:1px;


  background:#8ccfd0;


  border:2px solid #776080;


  transform:rotate(42deg);

}


.gpp-dropper::after{

  content:"";


  position:absolute;


  width:6px;

  height:6px;


  right:0;

  bottom:0;


  background:#ed8fb0;


  border:2px solid #776080;


  border-radius:50%;

}


/* LÍNEA */


.gpp-line::before{

  content:"";


  position:absolute;


  width:21px;

  height:3px;


  left:0;

  top:9px;


  background:#776080;


  transform:rotate(-43deg);

}


/* RECTÁNGULO */


.gpp-rectangle::before{

  content:"";


  position:absolute;


  width:18px;

  height:13px;


  left:1px;

  top:3px;


  border:3px solid #776080;

}


/* CÍRCULO */


.gpp-circle::before{

  content:"";


  position:absolute;


  width:17px;

  height:17px;


  left:1px;

  top:1px;


  border:3px solid #776080;


  border-radius:50%;

}


/* =====================================================

   LIENZO

   ===================================================== */


#gpp-canvas-zone{

  min-width:0;


  padding:8px;


  background:#fffaf8;

}


#gpp-canvas-frame{

  width:100%;


  height:220px;


  padding:4px;


  background:#fff;


  border:3px solid #c96f91;


  border-radius:4px;


  overflow:hidden;

}


#gpp-canvas{

  display:block;


  width:100%;

  height:100%;


  background-color:#fff;


  /*

     Cuadrícula pixel muy suave

  */


  background-image:

    linear-gradient(

      rgba(215,130,165,.16) 1px,

      transparent 1px

    ),

    linear-gradient(

      90deg,

      rgba(215,130,165,.16) 1px,

      transparent 1px

    );


  background-size:8px 8px;


  cursor:crosshair;


  touch-action:none;


  image-rendering:pixelated;

}


/* =====================================================

   BARRA DE INFORMACIÓN

   ===================================================== */


#gpp-info{

  height:24px;


  display:flex;

  align-items:center;


  padding:0 7px;


  border-top:2px solid #efb6c9;


  background:#f5fdf9;


  color:#8a657f;


  font-size:7px;

  font-weight:bold;


  white-space:nowrap;

  overflow:hidden;

}


/* =====================================================

   PALETA

   ===================================================== */


#gpp-palette-area{

  padding:7px 8px 6px;


  background:#fffdfc;


  border-top:3px solid #c96f91;

}


#gpp-palette{

  width:100%;


  display:flex;

  align-items:center;

  justify-content:center;


  gap:4px;


  flex-wrap:nowrap;

}


.gpp-color{

  width:21px;

  height:21px;


  flex:0 0 21px;


  padding:0;


  border:2px solid #80617b;


  border-radius:3px;


  cursor:pointer;

}


.gpp-color:hover{

  transform:translateY(-2px);

}


.gpp-color.active{

  outline:2px solid #c96f91;

  outline-offset:2px;

}


/* =====================================================

   TAMAÑOS

   ===================================================== */


#gpp-size-row{

  margin-top:6px;


  display:flex;

  align-items:center;

  justify-content:center;


  gap:5px;

}


#gpp-size-label{

  font-size:7px;

  font-weight:bold;

  color:#80617b;

}


.gpp-size{

  width:18px;

  height:18px;


  padding:0;


  display:flex;

  align-items:center;

  justify-content:center;


  border:2px solid #c96f91;

  border-radius:3px;


  background:#fff;


  cursor:pointer;

}


.gpp-size-dot{

  display:block;


  width:4px;

  height:4px;


  background:#6b5878;


  border-radius:50%;

}


.gpp-size:nth-child(3) .gpp-size-dot{

  width:7px;

  height:7px;

}


.gpp-size:nth-child(4) .gpp-size-dot{

  width:10px;

  height:10px;

}


.gpp-size:nth-child(5) .gpp-size-dot{

  width:13px;

  height:13px;

}


/* =====================================================

   BOTONES INFERIORES

   ===================================================== */


#gpp-actions{

  display:flex;


  gap:5px;


  padding:7px;


  background:#dff8ef;


  border-top:3px solid #c96f91;

}


.gpp-action{

  flex:1;


  height:30px;


  border:2px solid #c96f91;

  border-radius:4px;


  background:#fffaf8;


  color:#80617b;


  font-family:"Courier New",monospace;

  font-size:7px;

  font-weight:bold;


  cursor:pointer;

}


.gpp-action:hover{

  background:#ffe5ed;

}


.gpp-action:active{

  transform:translate(1px,1px);

}


/* =====================================================

   RESPONSIVE

   ===================================================== */


@media screen and (max-width:355px){


  #gema-pixel-paint,

  #gpp-window{

    width:100%;

  }


  #gpp-main{

    grid-template-columns:68px minmax(0,1fr);

  }


  #gpp-tools{

    padding-left:4px;

    padding-right:4px;

  }


  #gpp-canvas-zone{

    padding:6px;

  }


  #gpp-canvas-frame{

    height:210px;

  }


  .gpp-color{

    width:19px;

    height:19px;

    flex-basis:19px;

  }

}

</style>


<!-- =====================================================

     VENTANA

     ===================================================== -->


<div id="gpp-window">


  <!-- CABECERA -->


  <div id="gpp-header">


    <div id="gpp-name">

      <span id="gpp-name-heart">♡</span>

      <span>Gema's Pixel Paint</span>

    </div>


    <div id="gpp-window-buttons">


      <button

        type="button"

        class="gpp-window-btn"

        title="Minimizar">

      </button>


      <button

        type="button"

        class="gpp-window-btn"

        title="Restaurar">

      </button>


      <button

        type="button"

        class="gpp-window-btn"

        title="Cerrar">

      </button>


    </div>


  </div>


  <!-- MENÚ DECORATIVO -->


  <div id="gpp-menu">

    <span>File</span>

    <span>Edit</span>

    <span>View</span>

    <span>Image</span>

    <span>Options</span>

    <span>Help</span>

  </div>


  <!-- =================================================

       ZONA DE TRABAJO

       ================================================= -->


  <div id="gpp-main">


    <!-- HERRAMIENTAS -->


    <div id="gpp-tools">


      <button

        type="button"

        class="gpp-tool active"

        data-tool="pencil"

        title="Lápiz fino">


        <span class="gpp-icon gpp-pencil"></span>

        <span class="gpp-tool-label">LÁPIZ</span>


      </button>


      <button

        type="button"

        class="gpp-tool"

        data-tool="pencil-big"

        title="Lápiz grueso">


        <span class="gpp-icon gpp-pencil-big"></span>

        <span class="gpp-tool-label">GRUESO</span>


      </button>


      <button

        type="button"

        class="gpp-tool"

        data-tool="brush"

        title="Pincel">


        <span class="gpp-icon gpp-brush"></span>

        <span class="gpp-tool-label">PINCEL</span>


      </button>


      <button

        type="button"

        class="gpp-tool"

        data-tool="eraser"

        title="Borrador">


        <span class="gpp-icon gpp-eraser"></span>

        <span class="gpp-tool-label">BORRAR</span>


      </button>


      <button

        type="button"

        class="gpp-tool"

        data-tool="fill"

        title="Rellenar">


        <span class="gpp-icon gpp-fill"></span>

        <span class="gpp-tool-label">RELLENO</span>


      </button>


      <button

        type="button"

        class="gpp-tool"

        data-tool="dropper"

        title="Gotero">


        <span class="gpp-icon gpp-dropper"></span>

        <span class="gpp-tool-label">GOTERO</span>


      </button>


      <button

        type="button"

        class="gpp-tool"

        data-tool="line"

        title="Línea">


        <span class="gpp-icon gpp-line"></span>

        <span class="gpp-tool-label">LÍNEA</span>


      </button>


      <button

        type="button"

        class="gpp-tool"

        data-tool="rectangle"

        title="Rectángulo">


        <span class="gpp-icon gpp-rectangle"></span>

        <span class="gpp-tool-label">CUADRO</span>


      </button>


      <button

        type="button"

        class="gpp-tool"

        data-tool="circle"

        title="Círculo">


        <span class="gpp-icon gpp-circle"></span>

        <span class="gpp-tool-label">CÍRCULO</span>


      </button>


    </div>


    <!-- LIENZO -->


    <div id="gpp-canvas-zone">


      <div id="gpp-canvas-frame">


        <canvas

          id="gpp-canvas"

          width="620"

          height="500">

        </canvas>


      </div>


      <div id="gpp-info">

        #d97f9f · LÁPIZ FINO · 2px

      </div>


    </div>


  </div>

<!-- =====================================================

     GEMA'S PIXEL PAINT

     PARTE 2/4 — PALETA + TAMAÑOS + CONTROLES

     ===================================================== -->


  <!-- =================================================

       PALETA DE COLORES

       TODO permanece DENTRO DE LA VENTANA

       ================================================= -->


  <div id="gpp-palette-area">


    <div id="gpp-palette">


      <button

        type="button"

        class="gpp-color active"

        data-color="#d97f9f"

        title="Rosa"

        style="background:#d97f9f;">

      </button>


      <button

        type="button"

        class="gpp-color"

        data-color="#f2a65a"

        title="Durazno"

        style="background:#f2a65a;">

      </button>


      <button

        type="button"

        class="gpp-color"

        data-color="#f6d56f"

        title="Amarillo"

        style="background:#f6d56f;">

      </button>


      <button

        type="button"

        class="gpp-color"

        data-color="#a8dc83"

        title="Verde"

        style="background:#a8dc83;">

      </button>


      <button

        type="button"

        class="gpp-color"

        data-color="#82c8d0"

        title="Turquesa"

        style="background:#82c8d0;">

      </button>


      <button

        type="button"

        class="gpp-color"

        data-color="#86a8d9"

        title="Azul"

        style="background:#86a8d9;">

      </button>


      <button

        type="button"

        class="gpp-color"

        data-color="#a68bc5"

        title="Lila"

        style="background:#a68bc5;">

      </button>


      <button

        type="button"

        class="gpp-color"

        data-color="#80617b"

        title="Morado"

        style="background:#80617b;">

      </button>


      <button

        type="button"

        class="gpp-color"

        data-color="#33334a"

        title="Azul oscuro"

        style="background:#33334a;">

      </button>


      <button

        type="button"

        class="gpp-color"

        data-color="#ffffff"

        title="Blanco"

        style="background:#ffffff;">

      </button>


    </div>


    <!-- =============================================

         TAMAÑOS DE LÁPIZ

         ============================================= -->


    <div id="gpp-size-row">


      <span id="gpp-size-label">SIZE</span>


      <button

        type="button"

        class="gpp-size active"

        data-size="2"

        title="Tamaño pequeño">


        <span

          class="gpp-size-dot"

          style="width:3px;height:3px;">

        </span>


      </button>


      <button

        type="button"

        class="gpp-size"

        data-size="4"

        title="Tamaño mediano">


        <span

          class="gpp-size-dot"

          style="width:6px;height:6px;">

        </span>


      </button>


      <button

        type="button"

        class="gpp-size"

        data-size="7"

        title="Tamaño grande">


        <span

          class="gpp-size-dot"

          style="width:9px;height:9px;">

        </span>


      </button>


      <button

        type="button"

        class="gpp-size"

        data-size="12"

        title="Tamaño extra grande">


        <span

          class="gpp-size-dot"

          style="width:12px;height:12px;">

        </span>


      </button>


    </div>


  </div>


  <!-- =================================================

       BOTONES DE ACCIÓN

       TODOS DENTRO DEL ENCUADRE

       ================================================= -->


  <div id="gpp-actions">


    <button

      type="button"

      class="gpp-action"

      id="gpp-undo"

      title="Deshacer">


      ↶ UNDO


    </button>


    <button

      type="button"

      class="gpp-action"

      id="gpp-redo"

      title="Rehacer">


      ↷ REDO


    </button>


    <button

      type="button"

      class="gpp-action"

      id="gpp-clear"

      title="Limpiar todo">


      × CLEAR


    </button>


    <button

      type="button"

      class="gpp-action"

      id="gpp-save"

      title="Guardar dibujo">


      ♡ SAVE


    </button>


    <button

      type="button"

      class="gpp-action"

      id="gpp-png"

      title="Guardar como PNG">


      PNG


    </button>


  </div>


</div>


</div>


<!-- =====================================================

     FIN DE LA ESTRUCTURA HTML

     EL JAVASCRIPT FUNCIONAL VIENE EN 3/4 Y 4/4

     ===================================================== -->

<script>

/* =====================================================

   GEMA'S PIXEL PAINT

   PARTE 3/4 — MOTOR DE DIBUJO

   ===================================================== */


(function(){


  const paint = document.getElementById("gema-pixel-paint");


  if(!paint) return;


  const canvas = document.getElementById("gpp-canvas");

  const ctx = canvas.getContext("2d");


  ctx.imageSmoothingEnabled = false;


  /* ===================================================

     ESTADO

     =================================================== */


  let currentTool = "pencil";

  let currentColor = "#d97f9f";

  let brushSize = 2;


  let drawing = false;


  let startX = 0;

  let startY = 0;


  let lastX = 0;

  let lastY = 0;


  let history = [];

  let historyIndex = -1;


  /* ===================================================

     CONFIGURACIÓN DEL LIENZO

     =================================================== */


  function resetCanvas(){


    ctx.save();


    ctx.setTransform(1,0,0,1,0,0);


    ctx.fillStyle = "#ffffff";


    ctx.fillRect(

      0,

      0,

      canvas.width,

      canvas.height

    );


    ctx.restore();


    saveHistory();


  }


  /* ===================================================

     OBTENER POSICIÓN REAL DEL MOUSE / DEDO

     =================================================== */


  function getPosition(event){


    const rect = canvas.getBoundingClientRect();


    let clientX;

    let clientY;


    if(event.touches && event.touches.length){


      clientX = event.touches[0].clientX;

      clientY = event.touches[0].clientY;


    }else{


      clientX = event.clientX;

      clientY = event.clientY;


    }


    return {


      x:

        (clientX - rect.left)

        * (canvas.width / rect.width),


      y:

        (clientY - rect.top)

        * (canvas.height / rect.height)


    };


  }


  /* ===================================================

     ACTUALIZAR TEXTO INFERIOR

     =================================================== */


  function updateInfo(){


    const info = document.getElementById("gpp-info");


    if(!info) return;


    let name = "LÁPIZ FINO";


    if(currentTool === "pencil-big"){

      name = "LÁPIZ GRUESO";

    }


    if(currentTool === "brush"){

      name = "PINCEL";

    }


    if(currentTool === "eraser"){

      name = "BORRADOR";

    }


    if(currentTool === "fill"){

      name = "RELLENO";

    }


    if(currentTool === "dropper"){

      name = "GOTERO";

    }


    if(currentTool === "line"){

      name = "LÍNEA";

    }


    if(currentTool === "rectangle"){

      name = "RECTÁNGULO";

    }


    if(currentTool === "circle"){

      name = "CÍRCULO";

    }


    info.textContent =

      currentColor +

      " · " +

      name +

      " · " +

      brushSize +

      "px";


  }


  /* ===================================================

     HISTORIAL

     =================================================== */


  function saveHistory(){


    const image = canvas.toDataURL();


    if(historyIndex < history.length - 1){


      history =

        history.slice(0, historyIndex + 1);


    }


    history.push(image);


    if(history.length > 30){


      history.shift();


    }


    historyIndex =

      history.length - 1;


  }


  function restoreHistory(index){


    if(

      index < 0 ||

      index >= history.length

    ) return;


    const image = new Image();


    image.onload = function(){


      ctx.clearRect(

        0,

        0,

        canvas.width,

        canvas.height

      );


      ctx.drawImage(

        image,

        0,

        0

      );


    };


    image.src = history[index];


  }


  /* ===================================================

     UNDO

     =================================================== */


  document

    .getElementById("gpp-undo")

    .addEventListener("click",function(){


      if(historyIndex > 0){


        historyIndex--;


        restoreHistory(historyIndex);


      }


    });


  /* ===================================================

     REDO

     =================================================== */


  document

    .getElementById("gpp-redo")

    .addEventListener("click",function(){


      if(

        historyIndex <

        history.length - 1

      ){


        historyIndex++;


        restoreHistory(historyIndex);


      }


    });


  /* ===================================================

     CLEAR

     =================================================== */


  document

    .getElementById("gpp-clear")

    .addEventListener("click",function(){


      ctx.clearRect(

        0,

        0,

        canvas.width,

        canvas.height

      );


      ctx.fillStyle = "#ffffff";


      ctx.fillRect(

        0,

        0,

        canvas.width,

        canvas.height

      );


      saveHistory();


    });


  /* ===================================================

     GUARDAR PNG

     =================================================== */


  function downloadPNG(){


    const link =

      document.createElement("a");


    link.download =

      "gemas-pixel-paint.png";


    link.href =

      canvas.toDataURL("image/png");


    link.click();


  }


  document

    .getElementById("gpp-png")

    .addEventListener(

      "click",

      downloadPNG

    );


  document

    .getElementById("gpp-save")

    .addEventListener(

      "click",

      downloadPNG

    );


  /* ===================================================

     HERRAMIENTAS

     =================================================== */


  const tools =

    paint.querySelectorAll(".gpp-tool");


  tools.forEach(function(button){


    button.addEventListener(

      "click",

      function(){


        tools.forEach(function(item){


          item.classList.remove("active");


        });


        button.classList.add("active");


        currentTool =

          button.dataset.tool;


        updateInfo();


      }

    );


  });


  /* ===================================================

     COLORES

     =================================================== */


  const colors =

    paint.querySelectorAll(".gpp-color");


  colors.forEach(function(button){


    button.addEventListener(

      "click",

      function(){


        colors.forEach(function(item){


          item.classList.remove("active");


        });


        button.classList.add("active");


        currentColor =

          button.dataset.color;


        updateInfo();


      }

    );


  });


  /* ===================================================

     TAMAÑO

     =================================================== */


  const sizes =

    paint.querySelectorAll(".gpp-size");


  sizes.forEach(function(button){


    button.addEventListener(

      "click",

      function(){


        sizes.forEach(function(item){


          item.classList.remove("active");


        });


        button.classList.add("active");


        brushSize =

          Number(button.dataset.size);


        updateInfo();


      }

    );


  });


  /* ===================================================

     CONFIGURAR TRAZO

     =================================================== */


  function configureBrush(){


    ctx.lineCap = "round";

    ctx.lineJoin = "round";


    ctx.lineWidth =

      brushSize;


    if(currentTool === "pencil"){


      ctx.lineWidth =

        brushSize;


    }


    if(currentTool === "pencil-big"){


      ctx.lineWidth =

        Math.max(brushSize * 2,5);


    }


    if(currentTool === "brush"){


      ctx.lineWidth =

        Math.max(brushSize * 3,8);


    }


    if(currentTool === "eraser"){


      ctx.lineWidth =

        Math.max(brushSize * 2,8);


    }


    if(currentTool === "eraser"){


      ctx.globalCompositeOperation =

        "destination-out";


    }else{


      ctx.globalCompositeOperation =

        "source-over";


    }


  }


  /* ===================================================

     DIBUJAR LÍNEA LIBRE

     =================================================== */


  function drawFreehand(x,y){


    configureBrush();


    ctx.strokeStyle =

      currentColor;


    ctx.beginPath();


    ctx.moveTo(

      lastX,

      lastY

    );


    ctx.lineTo(

      x,

      y

    );


    ctx.stroke();


    lastX = x;

    lastY = y;


  }


  /* ===================================================

     RELLENO

     =================================================== */


  function floodFill(x,y){


    const imageData =

      ctx.getImageData(

        0,

        0,

        canvas.width,

        canvas.height

      );


    const data =

      imageData.data;


    const px =

      Math.floor(x);


    const py =

      Math.floor(y);


    const start =

      (py * canvas.width + px) * 4;


    const target = [


      data[start],

      data[start + 1],

      data[start + 2],

      data[start + 3]


    ];


    const temp =

      document.createElement("canvas");


    temp.width =

      canvas.width;


    temp.height =

      canvas.height;


    const tempCtx =

      temp.getContext("2d");


    tempCtx.putImageData(

      imageData,

      0,

      0

    );


    function hexToRGBA(hex){


      hex =

        hex.replace("#","");


      return [


        parseInt(

          hex.substring(0,2),

          16

        ),


        parseInt(

          hex.substring(2,4),

          16

        ),


        parseInt(

          hex.substring(4,6),

          16

        ),


        255


      ];


    }


    const fill =

      hexToRGBA(currentColor);


    if(

      target[0] === fill[0] &&

      target[1] === fill[1] &&

      target[2] === fill[2]

    ){


      return;


    }


    const stack = [

      [px,py]

    ];


    const visited =

      new Uint8Array(

        canvas.width *

        canvas.height

      );


    function matches(index){


      return (


        data[index] === target[0] &&

        data[index + 1] === target[1] &&

        data[index + 2] === target[2] &&

        data[index + 3] === target[3]


      );


    }


    while(stack.length){


      const point =

        stack.pop();


      const cx =

        point[0];


      const cy =

        point[1];


      if(

        cx < 0 ||

        cy < 0 ||

        cx >= canvas.width ||

        cy >= canvas.height

      ) continue;


      const pixelIndex =

        cy * canvas.width + cx;


      if(visited[pixelIndex]) continue;


      visited[pixelIndex] = 1;


      const index =

        pixelIndex * 4;


      if(!matches(index)) continue;


      data[index] =

        fill[0];


      data[index + 1] =

        fill[1];


      data[index + 2] =

        fill[2];


      data[index + 3] =

        fill[3];


      stack.push([cx + 1,cy]);

      stack.push([cx - 1,cy]);

      stack.push([cx,cy + 1]);

      stack.push([cx,cy - 1]);


    }


    ctx.putImageData(

      imageData,

      0,

      0

    );


  }


  /* ===================================================

     GOTERO

     =================================================== */


  function pickColor(x,y){


    const pixel =

      ctx.getImageData(

        Math.floor(x),

        Math.floor(y),

        1,

        1

      ).data;


    currentColor =

      "#" +

      [pixel[0],pixel[1],pixel[2]]

        .map(function(value){


          return value

            .toString(16)

            .padStart(2,"0");


        })

        .join("");


    colors.forEach(function(button){


      button.classList.remove("active");


      if(

        button.dataset.color.toLowerCase() ===

        currentColor.toLowerCase()

      ){


        button.classList.add("active");


      }


    });


    updateInfo();


  }


  /* ===================================================

     INICIO DEL DIBUJO

     =================================================== */


  function startDrawing(event){


    event.preventDefault();


    const pos =

      getPosition(event);


    startX = pos.x;

    startY = pos.y;


    lastX = pos.x;

    lastY = pos.y;


    if(currentTool === "fill"){


      floodFill(

        pos.x,

        pos.y

      );


      saveHistory();


      return;


    }


    if(currentTool === "dropper"){


      pickColor(

        pos.x,

        pos.y

      );


      return;


    }


    drawing = true;


    if(

      currentTool === "pencil" ||

      currentTool === "pencil-big" ||

      currentTool === "brush" ||

      currentTool === "eraser"

    ){


      configureBrush();


      ctx.strokeStyle =

        currentColor;


      ctx.beginPath();


      ctx.arc(

        pos.x,

        pos.y,

        ctx.lineWidth / 2,

        0,

        Math.PI * 2

      );


      ctx.fillStyle =

        currentColor;


      if(currentTool === "eraser"){


        ctx.fillStyle =

          "rgba(0,0,0,1)";


      }


      ctx.fill();


    }


  }


  /* ===================================================

     MOVIMIENTO

     =================================================== */


  function moveDrawing(event){


    if(!drawing) return;


    event.preventDefault();


    const pos =

      getPosition(event);


    if(

      currentTool === "pencil" ||

      currentTool === "pencil-big" ||

      currentTool === "brush" ||

      currentTool === "eraser"

    ){


      drawFreehand(

        pos.x,

        pos.y

      );


    }


  }


  /* ===================================================

     FIN DEL DIBUJO

     =================================================== */


  function stopDrawing(event){


    if(!drawing) return;


    event.preventDefault();


    const pos =

      getPosition(event);


    if(

      currentTool === "line" ||

      currentTool === "rectangle" ||

      currentTool === "circle"

    ){


      ctx.globalCompositeOperation =

        "source-over";


      ctx.strokeStyle =

        currentColor;


      ctx.lineWidth =

        brushSize;


      ctx.lineCap =

        "round";


      ctx.lineJoin =

        "round";


      if(currentTool === "line"){


        ctx.beginPath();


        ctx.moveTo(

          startX,

          startY

        );


        ctx.lineTo(

          pos.x,

          pos.y

        );


        ctx.stroke();


      }


      if(currentTool === "rectangle"){


        ctx.strokeRect(


          startX,

          startY,


          pos.x - startX,

          pos.y - startY


        );


      }


      if(currentTool === "circle"){


        const dx =

          pos.x - startX;


        const dy =

          pos.y - startY;


        const radius =

          Math.sqrt(

            dx * dx +

            dy * dy

          );


        ctx.beginPath();


        ctx.arc(

          startX,

          startY,

          radius,

          0,

          Math.PI * 2

        );


        ctx.stroke();


      }


    }


    drawing = false;


    ctx.globalCompositeOperation =

      "source-over";


    saveHistory();


  }


  /* ===================================================

     EVENTOS DEL MOUSE

     =================================================== */


  canvas.addEventListener(

    "mousedown",

    startDrawing

  );


  canvas.addEventListener(

    "mousemove",

    moveDrawing

  );


  canvas.addEventListener(

    "mouseup",

    stopDrawing

  );


  canvas.addEventListener(

    "mouseleave",

    stopDrawing

  );


  /* ===================================================

     EVENTOS TÁCTILES

     =================================================== */


  canvas.addEventListener(

    "touchstart",

    startDrawing,

    {passive:false}

  );


  canvas.addEventListener(

    "touchmove",

    moveDrawing,

    {passive:false}

  );


  canvas.addEventListener(

    "touchend",

    stopDrawing,

    {passive:false}

  );


  /* ===================================================

     INICIAR

     =================================================== */


  resetCanvas();


  updateInfo();


})();

</script>

<script>

/* =====================================================

   GEMA'S PIXEL PAINT

   PARTE 4/4 — DETALLES FINALES + SEGURIDAD

   ===================================================== */


(function(){


  const paint =

    document.getElementById("gema-pixel-paint");


  if(!paint) return;


  /* ===================================================

     EVITAR QUE LOS BOTONES RECARGUEN EL BLOG

     =================================================== */


  paint

    .querySelectorAll("button")

    .forEach(function(button){


      button.setAttribute(

        "type",

        "button"

      );


    });


  /* ===================================================

     BOTÓN CLEAR

     CONFIRMACIÓN SUAVE

     =================================================== */


  const clear =

    document.getElementById("gpp-clear");


  if(clear){


    clear.addEventListener(

      "dblclick",

      function(event){


        event.preventDefault();


      }

    );


  }


  /* ===================================================

     BOTÓN SAVE

     PEQUEÑA CONFIRMACIÓN VISUAL

     =================================================== */


  const save =

    document.getElementById("gpp-save");


  if(save){


    save.addEventListener(

      "click",

      function(){


        const original =

          save.innerHTML;


        save.innerHTML =

          "✓ SAVED";


        setTimeout(function(){


          save.innerHTML =

            original;


        },1200);


      }

    );


  }


  /* ===================================================

     BOTÓN PNG

     =================================================== */


  const png =

    document.getElementById("gpp-png");


  if(png){


    png.addEventListener(

      "click",

      function(){


        const original =

          png.innerHTML;


        png.innerHTML =

          "✓ PNG";


        setTimeout(function(){


          png.innerHTML =

            original;


        },1200);


      }

    );


  }


  /* ===================================================

     BOTONES DE VENTANA

     

     NO CAMBIAN NADA DEL BLOG.

     SOLO CONTROLAN EL MINI PAINT.

     =================================================== */


  const header =

    document.getElementById("gpp-header");


  const main =

    document.getElementById("gpp-main");


  const palette =

    document.getElementById("gpp-palette-area");


  const actions =

    document.getElementById("gpp-actions");


  const menu =

    document.getElementById("gpp-menu");


  const windowButtons =

    paint.querySelectorAll(

      ".gpp-window-btn"

    );


  /* ===================================================

     MINIMIZAR

     =================================================== */


  if(windowButtons[0]){


    windowButtons[0].addEventListener(

      "click",

      function(){


        const hidden =

          main.style.display === "none";


        if(hidden){


          main.style.display =

            "grid";


          palette.style.display =

            "block";


          actions.style.display =

            "flex";


          menu.style.display =

            "flex";


        }else{


          main.style.display =

            "none";


          palette.style.display =

            "none";


          actions.style.display =

            "none";


          menu.style.display =

            "none";


        }


      }

    );


  }


  /* ===================================================

     RESTAURAR

     =================================================== */


  if(windowButtons[1]){


    windowButtons[1].addEventListener(

      "click",

      function(){


        main.style.display =

          "grid";


        palette.style.display =

          "block";


        actions.style.display =

          "flex";


        menu.style.display =

          "flex";


      }

    );


  }


  /* ===================================================

     CERRAR

     

     En lugar de cerrar el gadget del blog,

     solo lo convierte en una pequeña ventana

     que puede volver a abrirse.

     =================================================== */


  if(windowButtons[2]){


    windowButtons[2].addEventListener(

      "click",

      function(){


        main.style.display =

          "none";


        palette.style.display =

          "none";


        actions.style.display =

          "none";


        menu.style.display =

          "none";


        header.style.borderBottom =

          "3px solid #c96f91";


      }

    );


  }


  /* ===================================================

     DOBLE CLIC EN EL NOMBRE

     RESTAURA LA VENTANA

     =================================================== */


  const name =

    document.getElementById("gpp-name");


  if(name){


    name.addEventListener(

      "dblclick",

      function(){


        main.style.display =

          "grid";


        palette.style.display =

          "block";


        actions.style.display =

          "flex";


        menu.style.display =

          "flex";


      }

    );


  }


  /* ===================================================

     EVITAR ARRASTRE DE ELEMENTOS DEL BLOG

     =================================================== */


  paint.addEventListener(

    "dragstart",

    function(event){


      event.preventDefault();


    }

  );


  /* ===================================================

     EVITAR QUE EL MINI PAINT AFECTE EL SCROLL

     DEL BLOG CUANDO SE ESTÁ DIBUJANDO

     =================================================== */


  const canvas =

    document.getElementById("gpp-canvas");


  if(canvas){


    canvas.style.webkitUserSelect =

      "none";


    canvas.style.userSelect =

      "none";


    canvas.style.webkitTouchCallout =

      "none";


  }


  /* ===================================================

     MENSAJE INICIAL

     =================================================== */


  const info =

    document.getElementById("gpp-info");


  if(info){


    setTimeout(function(){


      info.textContent =

        "#d97f9f · LISTO PARA DIBUJAR · 2px";


    },100);


  }


})();

</script>


<!-- =====================================================

     FIN DE GEMA'S PIXEL PAINT

     ===================================================== -->

Guia 

Cómo cambiar nombre, colores, paleta, textos y tamaños sin romper el funcionamiento del gadget.
ANTES DE EMPEZAR
El código está dividido en 4 partes:
• PARTE 1/4: diseño, ventana, herramientas y lienzo.
• PARTE 2/4: paleta de colores, tamaños y botones.
• PARTE 3/4: funciones principales del dibujo.
• PARTE 4/4: funciones de la ventana y detalles finales.
Para personalizar la apariencia, principalmente trabajarás con las PARTES 1/4 y 2/4. Las PARTES 3/4 y 4/4 contienen
JavaScript, que hace funcionar el Mini Paint.
1. CAMBIAR EL NOMBRE DEL MINI PAINT
En la PARTE 1/4, dentro de la cabecera, busca:
<span>Gema's Pixel Paint</span>
Cambia únicamente el texto entre las etiquetas:
<span>Mi Mini Paint ■</span>
No borres las etiquetas <span> y </span>.
2. CAMBIAR LOS COLORES PRINCIPALES
Los colores están principalmente en la PARTE 1/4, dentro de <style>. Los códigos hexadecimales actuales incluyen:
• #c96f91 → rosa
• #dff8ef → verde menta
• #fffaf8 → crema claro
• #80617b → morado grisáceo
• #ffffff → blanco
Color de los bordes:
border:3px solid #c96f91;
Fondo principal:
background:#fffaf8;
Fondo menta:
background:#dff8ef;
Colores de texto:
color:#b85e80;
color:#80617b;
3. CAMBIAR LOS COLORES DE LA PALETA
En la PARTE 2/4, cada color tiene dos lugares que deben coincidir:data-color="#f2a65a"
style="background:#f2a65a;"
Si cambias el color, cambia ambos. Por ejemplo:
data-color="#ffb3c6"
style="background:#ffb3c6;"
4. CAMBIAR EL NOMBRE DE UN COLOR
Busca title="Durazno" y cámbialo por el nombre que quieras, por ejemplo title="Rosa pastel".
5. AGREGAR O QUITAR COLORES
Puedes duplicar un botón de la paleta y cambiar su color y nombre. Evita agregar demasiados colores porque la paleta
está diseñada para mantenerse dentro de la ventana.
6. CAMBIAR LOS TAMAÑOS DEL LÁPIZ
En la PARTE 2/4 encontrarás valores como:
data-size="2"
data-size="4"
data-size="7"
data-size="12"
Representan diferentes tamaños del pincel. Por ejemplo, data-size="2" significa 2 px.
7. CAMBIAR TEXTOS DE HERRAMIENTAS
Puedes modificar los nombres visibles, por ejemplo:
<span class="gpp-tool-label">LÁPIZ</span>
Puedes personalizar LÁPIZ, GRUESO, PINCEL, BORRAR, RELLENO, GOTERO, LÍNEA, CUADRO y CÍRCULO.
8. CAMBIAR EL ANCHO DEL GADGET
Al principio de la PARTE 1/4:
#gema-pixel-paint{ width:345px; }
#gpp-window{ width:345px; }
Puedes modificar 345px, pero debe respetar el ancho disponible de la sidebar para que no se salga.
9. CAMBIAR EL TAMAÑO DEL LIENZO
El tamaño interno aparece como:
<canvas id="gpp-canvas" width="620" height="500">
Y el espacio visual del marco usa, entre otros valores:
#gpp-canvas-frame{ height:220px; }
No recomiendo cambiar estos valores si no es necesario porque están relacionados con la adaptación del lienzo.
10. CAMBIAR EL NOMBRE DEL ARCHIVO PNG
En la PARTE 3/4 busca:link.download = "gemas-pixel-paint.png";
Puedes cambiarlo por, por ejemplo:
link.download = "mi-dibujo.png";
11. CAMBIAR EL TEXTO DE INFORMACIÓN
Debajo del lienzo aparece información como: #d97f9f · LÁPIZ FINO · 2px. Se actualiza automáticamente según la
herramienta, color y tamaño. No es recomendable modificar el JavaScript que lo actualiza.
12. CAMBIAR LOS BOTONES DE LA VENTANA
Los tres botones superiores tienen estos colores:
.gpp-window-btn{ background:#ffd979; }
.gpp-window-btn:nth-child(2){ background:#9bdc79; }
.gpp-window-btn:nth-child(3){ background:#ed8fb0; }
13. CAMBIAR EL MENÚ DECORATIVO
Puedes cambiar File, Edit, View, Image, Options y Help directamente en la PARTE 1/4. Es un menú decorativo y no tiene
funciones propias.
14. CAMBIAR EL CORAZÓN DE LA CABECERA
Busca: <span id="gpp-name-heart">■</span> y cambia únicamente el símbolo por ♥, ✦, ■, etc. No cambies el id.
15. CAMBIAR LOS NOMBRES DE LOS BOTONES INFERIORES
Puedes cambiar los textos UNDO, REDO, CLEAR, SAVE y PNG. No cambies los id como gpp-save, gpp-clear, gpp-undo
o gpp-redo, porque JavaScript los utiliza.
16. ¿QUÉ NO DEBERÍA MODIFICAR?
NO MODIFICAR LOS id. Por ejemplo: id="gpp-canvas", id="gpp-save", id="gpp-clear" e id="gpp-undo". Estos
identificadores conectan el HTML con JavaScript.
NO MODIFICAR data-tool. Valores como data-tool="pencil", data-tool="eraser", data-tool="fill" y data-tool="dropper"
indican qué herramienta se está usando.
NO MODIFICAR LA PARTE 3/4 SIN SABER JAVASCRIPT. Ahí están el dibujo, borrador, pincel, relleno, gotero, líneas,
figuras, historial, undo, redo, guardar, PNG y funcionamiento táctil.
NO MODIFICAR LA PARTE 4/4. Controla minimizar, restaurar, cerrar, mensajes visuales, comportamiento de botones,
interacción táctil y otros detalles.

REGLA PRINCIPAL
Si quieres cambiar cómo se ve → PARTE 1/4 y PARTE 2/4.
Si quieres cambiar cómo funciona → PARTE 3/4 y PARTE 4/4.
Si no sabes JavaScript, no modifiques las PARTES 3/4 y 4/4, porque ahí es donde es más fácil hacer que alguna
herramienta deje de funcionar.


No hay comentarios.:

Publicar un comentario