Created
February 5, 2025 01:58
-
-
Save porfidev/9cf5f4661ec31a610423b72f58cb0e2c to your computer and use it in GitHub Desktop.
Chart.js with button to download Graph
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
import {useEffect, useRef} from 'react'; | |
import Chart from "chart.js/auto"; | |
const Graph = () => { | |
const canvasRef = useRef<HTMLCanvasElement | null>(null); | |
const handleDownload = async () => { | |
if(!canvasRef.current) { | |
return; | |
} | |
const link = document.createElement("a"); | |
const base64Image = canvasRef.current.toDataURL("image/png", 1); | |
link.download = 'grafica.png'; | |
link.href = base64Image; | |
// link.click(); | |
// Convertir el base64 a un objeto Blob | |
const blob = await (await fetch(base64Image)).blob(); | |
console.log('BLOB', blob); | |
const formData = new FormData(); | |
formData.append("image", blob, "grafica.png"); // Nombre del archivo | |
console.log('FormData', formData); | |
try { | |
// Enviar la solicitud HTTP | |
const response = await fetch("https://tu-servicio.com/api/upload", { | |
method: "POST", | |
body: formData, | |
}); | |
if (response.ok) { | |
console.log("Imagen enviada con éxito"); | |
} else { | |
console.error("Error al enviar la imagen", response.statusText); | |
} | |
} catch (error) { | |
console.error("Error en la solicitud:", error); | |
} | |
}; | |
useEffect(() => { | |
const ctx = canvasRef.current?.getContext("2d"); | |
if (ctx) { | |
// Crear la gráfica | |
const chartInstance = new Chart(ctx, { | |
type: "bar", // Tipo de gráfica | |
data: { | |
labels: ["Enero", "Febrero", "Marzo", "Abril", "Mayo"], | |
datasets: [ | |
{ | |
label: "Ventas ($)", | |
data: [5000, 7000, 8000, 6000, 9000], | |
backgroundColor: "rgba(75, 192, 192, 0.6)", // Color de las barras | |
borderColor: "rgba(75, 192, 192, 1)", // Color del borde | |
borderWidth: 1, // Grosor del borde | |
}, | |
], | |
}, | |
options: { | |
responsive: true, | |
plugins: { | |
legend: { | |
position: "top", | |
}, | |
title: { | |
display: true, | |
text: "Ventas Mensuales", | |
}, | |
}, | |
}, | |
}); | |
// Limpiar el gráfico al desmontar el componente | |
return () => { | |
chartInstance.destroy(); | |
}; | |
} | |
}, []); | |
return (<div><canvas ref={canvasRef} width={640} height={480} /> | |
<button onClick={handleDownload}>Descargar</button> | |
</div>) | |
} | |
export default Graph; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment