I have written the following code to create a JPG image file that prints the gradient background of the HTML body as the image background:
const downloadButton = document.getElementById('downloadButton');
downloadButton.addEventListener('click', function() {
// Create a canvas element and set its dimensions
const canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 300;
// Get the canvas context
const ctx = canvas.getContext('2d');
// Fill the canvas with the background Image
const bodyStyle = document.body.style;
const backgroundImage = bodyStyle.backgroundImage || 'white'; // Default to white if not set
ctx.fillStyle = backgroundImage;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Add text indicating background Image
ctx.font = '20px Arial';
ctx.fillStyle = 'black';
const rgbColor = getRGBColor(backgroundImage); // Convert to RGB format
ctx.fillText(`background Image : ${rgbColor}`, 200, 250); // Adjust position as needed
// Convert the canvas to a data URL (PNG format)
const dataURL = canvas.toDataURL('image/jpg');
// Convert the data URL to a Blob object
const blob = new Blob([dataURL.split(',')[1]], { type: 'image/jpg' });
// Create a temporary URL for the Blob object
const fileURL = URL.createObjectURL(blob);
// Trigger the download of the JPG file
const link = document.createElement('a');
link.href = fileURL;
link.download = 'image.jpg';
link.click();
// Revoke the temporary URL when done (optional)
URL.revokeObjectURL(fileURL);
});
// Function to convert hex color to RGB format
function getRGBColor(hexColor) {
if (hexColor.length === 3) {
hexColor = hexColor.repeat(2); // Duplicate for full RGB
}
const r = parseInt(hexColor.slice(0, 2), 16);
const g = parseInt(hexColor.slice(2, 4), 16);
const b = parseInt(hexColor.slice(4, 6), 16);
return `rgb(${r}, ${g}, ${b})`;
}
It creates a file named image.jpg, but it doesn’t open with any tool !?
My goal is simply to create a .jpg file that can render the background of the HTML body, which is:
body {
background-image : linear-gradient(0deg ,rgb(0,0,153), rgb(107,0,0));
}