Como crear un meme con html5 y javascript

Iniciado por graphixx, Enero 27, 2016, 02:00:14 PM

Tema anterior - Siguiente tema

0 Miembros y 2 Visitantes están viendo este tema.

Enero 27, 2016, 02:00:14 PM Ultima modificación: Enero 27, 2016, 04:19:21 PM por EPSILON

De manera sencilla vamos a crear los famosos MEME lo cual podría ser "imágenes para que se le agrega un texto para hacer una broma gráfica o joda".

Explicación breve:
Antes de entrar al código y me digan, pero podemos agregar esto y lo otro .. esto es un EJEMPLO señores, el cual la idea es que ustedes lo puedan mejorar.

En que consiste:
Se sube una imagen, se agrega un texto y genera la imagen para luego descargarla dando click derecho.

Ahora si:
Toda nuestra lógica se resume al siguiente script

Código: javascript

var img, canvas, context;
       
        function SubirImagen()
        {
            canvas = document.getElementById("canvas");
            context = canvas.getContext("2d");
           
            canvas.width = 700;
            canvas.height = 500;
           
            // Cargamos el objeto que nos permite subir imagenes
            var imagen = document.getElementById("imagen");
            if(imagen.files.length == 0)
            {
                alert('Debe ingresar una imagen');
                return;
            }

            // Creamos la imagen
            img = new Image();
            img.src = URL.createObjectURL(imagen.files[0]);
           
            img.onload = function() {
                // Dibujamos la imagen
                context.drawImage(img, 0, 0, canvas.width, canvas.height);
            };
           
            // Mostramos el canvas
            document.getElementById("meme").style.display = 'block';
        }
       
        function AgregarTexto()
        {
            // Cargamos la caja de texto
            var texto = document.getElementById("texto");
           
            img.src = URL.createObjectURL(imagen.files[0]);
            img.onload = function() {
                // Dibujamos la imagen
                context.drawImage(img, 0, 0, canvas.width, canvas.height);
               
                // Agregamos el texto
                context.lineWidth  = 5;
                context.font = '30pt sans-serif';
                context.strokeStyle = 'black';
                context.fillStyle = 'white';
                context.textAlign = 'center';

                texto = texto.value.toUpperCase();
               
                var x = canvas.width/2;
                var y = canvas.height - 40;

                context.strokeText(texto, x, y);
                context.fillText(texto, x, y);
            };
        }



  • Declaramos 2 variables globales ya que ahí guardaremos al objeto canvas y nuestro contexto a usar.
  • La función SubirImagen() lo que hace es al momento de seleccionar un imagen mediante el input file, este la renderiza en nuestro objeto canvas.
  • La función AgregarTexto() lo que hace es que cuando se escriba algo en nuestra caja de texto vuelva a cargar la imagen más el texto agregado en nuestro objeto canvas.

En la función AgregarTexto() he agregado comentarios para que se entienda mejor:

Código: javascript

context.lineWidth  = 5; // Grosor del borde
context.font = '30pt sans-serif'; // tamaño de letra y tipo de fuente
context.strokeStyle = 'black'; // color de la sombra
context.fillStyle = 'white'; // color del texto
context.textAlign = 'center'; // alineación del texto

texto = texto.value.toUpperCase(); // lo pasamos a mayascula

var x = canvas.width/2; // para decirle que el texto comience justo al medio
var y = canvas.height - 40; // le decimos que el texto comience al final menos ¿40px?

context.strokeText(texto, x, y); // creamos la sombra
context.fillText(texto, x, y); // creamos el texto


Nuestro código html es muy simple

Código: html5

<div id="subida">
    <p id="elija">SELECCIONE UNA IMAGEN A SUBIR</p>
    <div class="form-control">
        <input id="imagen" type="file" />
    </div>
    <div class="form-control">
        <button id="subir" onclick="SubirImagen();">Renderizar</button>
    </div>
</div>
<div id="meme" class="none">
    <div class="form-control">
        <input id="texto" type="text" onkeyup="AgregarTexto();" placeholder="Texto que desea agregar" maxlength="20" autocomplete="off" />
    </div>
    <canvas id="canvas"></canvas>
    <div class="form-control">
        <p><b>Click derecho</b> y <b>guardar imagen como</b> para descargar</p>
    </div>
</div>


You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login

Fuente: You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login
Mi Blog Personal
You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login

Muy bueno!! muchas gracias @You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login :D