Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Last active July 25, 2021 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/4f6f31921592d9dfb1b0dc6749bd99be to your computer and use it in GitHub Desktop.
Save parzibyte/4f6f31921592d9dfb1b0dc6749bd99be to your computer and use it in GitHub Desktop.
<!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