-
-
Save parzibyte/b8ea028d051c0f9a8976dc6669067171 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="es"> | |
<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>Enviar canvas de JavaScript a PHP</title> | |
</head> | |
<body> | |
<canvas id="canvas"></canvas> | |
<br> | |
<button id="btnEnviar">Enviar a PHP</button> | |
<script> | |
const ALTURA_CANVAS = 200, | |
ANCHURA_CANVAS = 400; | |
const $btnEnviar = document.querySelector("#btnEnviar"); | |
const $canvas = document.querySelector("#canvas"); | |
// Simple función que dibuja algo en el canvas, solo de ejemplo | |
// Tomado de: https://parzibyte.me/blog/2019/07/16/dibujar-figuras-geometricas-canvas-javascript/ | |
const dibujarEnCanvas = () => { | |
// Obtener el elemento del DOM | |
$canvas.width = ANCHURA_CANVAS; | |
$canvas.height = ALTURA_CANVAS; | |
// Del canvas, obtener el contexto para poder dibujar | |
const contexto = $canvas.getContext("2d"); | |
// Estilo de dibujo | |
// Grosor de línea | |
contexto.lineWidth = 5; | |
// Color de línea | |
contexto.strokeStyle = "#212121"; | |
// Color de relleno | |
contexto.fillStyle = "#D4E157"; | |
// Comenzamos la ruta de dibujo, o path | |
contexto.beginPath(); | |
// Esquina superior izquierda | |
contexto.moveTo(35, 5); | |
// Línea recta superior | |
contexto.lineTo(95, 5); | |
// Esquina central derecha | |
contexto.lineTo(125, 55); | |
// Esquina inferior derecha | |
contexto.lineTo(95, 105); | |
// Línea recta inferior | |
contexto.lineTo(35, 105); | |
// Esquina central izquierda | |
contexto.lineTo(5, 55); | |
// Y dejamos que la última línea la dibuje JS | |
contexto.closePath(); | |
// Hacemos que se dibuje | |
contexto.stroke(); | |
// Lo rellenamos | |
contexto.fill(); | |
} | |
$btnEnviar.onclick = async () => { | |
// Convertir la imagen a Base64 y ponerlo en el enlace | |
const data = $canvas.toDataURL("image/png"); | |
const fd = new FormData(); | |
fd.append("imagen", data); // Se llama "imagen", en PHP lo recuperamos con $_POST["imagen"] | |
const respuestaHttp = await fetch("imagen.php", { | |
method: "POST", | |
body: fd, | |
}); | |
const nombreImagenSubida = await respuestaHttp.json(); | |
console.log("La imagen ha sido enviada y tiene el nombre de: " + nombreImagenSubida); | |
}; | |
dibujarEnCanvas(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment