-
-
Save parzibyte/4f6f31921592d9dfb1b0dc6749bd99be 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> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>Canvas a imagen</title> | |
</head> | |
<body> | |
<h1>Canvas a JPG</h1> | |
<canvas id="canvas"></canvas> | |
<button id="btnDescargar">Descargar</button> | |
<script> | |
const $canvas = document.querySelector("#canvas"), | |
$btnDescargar = document.querySelector("#btnDescargar"); | |
// Lo siguiente dibuja en el canvas, no tiene que ver con el tutorial, solo es demostración | |
const contexto = $canvas.getContext("2d"); | |
contexto.strokeStyle = "red"; | |
contexto.beginPath(); | |
contexto.arc(95, 50, 40, 0, 2 * Math.PI); | |
contexto.stroke(); | |
// Listener del botón | |
$btnDescargar.addEventListener("click", () => { | |
// Crear un elemento <a> | |
let enlace = document.createElement('a'); | |
// El título | |
enlace.download = "Canvas como imagen.jpg"; | |
// Convertir la imagen a Base64 y ponerlo en el enlace | |
enlace.href = canvas.toDataURL("image/jpeg", 1); | |
// Hacer click en él | |
enlace.click(); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment