Создание градиентного фона в файле изображения, сгенерированном JavaScriptJquery

Программирование на jquery
Ответить Пред. темаСлед. тема
Anonymous
 Создание градиентного фона в файле изображения, сгенерированном JavaScript

Сообщение Anonymous »

Я написал следующий код для создания файла изображения PNG, который печатает градиентный фон тела HTML в качестве фона изображения:
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/png');

// Convert the data URL to a Blob object
const blob = new Blob([dataURL.split(',')[1]], { type: 'image/png' });

// 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.png';
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})`;
}

Он создает файл с именем image.png, но не открывается никаким инструментом!?
Мой цель состоит в том, чтобы просто создать файл .png, который может отображать фон тела HTML, а именно:
body {
background-image : linear-gradient(0deg ,rgb(0,0,153), rgb(107,0,0));
}


Изменить:
Моя главная цель — не отображать фон тела HTML!
Я написал код, который генерирует код градиента и отображает его на экране следующим образом: (часть моего кода)
if (selectedRadio.value === 'option8') {
gradientString = "-webkit-linear-gradient(" + rot + "deg, rgb(" + red1 + "," + green1 + "," + blue1 + "), rgb(" + red2 + "," + green2 + "," + blue2 + "), rgb(" + red3 + "," + green3 + "," + blue3 + "), rgb(" + red4 + "," + green4 + "," + blue4 + ") , rgb(" + red5 + "," + green5 + "," + blue5 + "), rgb(" + red6 + "," + green6 + "," + blue6 + "), rgb(" + red7 + " ," + green7 + "," + blue7 + "), rgb(" + red8 + "," + green8 + "," + blue8 + "))";
}

document.getElementById('result').style.backgroundSize = 'cover';
document.getElementById('result').style.backgroundImage = gradientString;

Теперь я хочу создать такой же результат в файле изображения.

Edit2:
Я изменил код, как показано ниже, для достижения своей цели, но файл для меня больше не создается?
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');

// Create a gradient object using gradientString
const gradient = new LinearGradient(0, 0, canvas.width, canvas.height); // Adjust coordinates for desired direction
const gradientParts = gradientString.split(',');
for (let i = 1; i < gradientParts.length; i++) {
const colorStop = gradientParts.trim().split(')')[0].split(' ');
const color = colorStop[1];
const position = parseFloat(colorStop[0].slice(0, -1));
gradient.addColorStop(position, color);
}

// Set the fill style of the canvas context to the gradient
ctx.fillStyle = gradient;

// Fill the canvas with the gradient
ctx.fillRect(0, 0, canvas.width, canvas.height);

// Add text indicating gradientString content (optional)
ctx.font = '16px Arial';
ctx.fillStyle = 'black';
ctx.fillText(`Gradient String: ${gradientString.slice(0, 50) + "..."}`, 10, 20); // Adjust position and truncate string as needed

// Convert the canvas to a Blob object using canvas.toBlob()
canvas.toBlob((blob) => {
// Create a temporary URL for the Blob object
const fileURL = URL.createObjectURL(blob);

// Trigger the download of the PNG file
const link = document.createElement('a');
link.href = fileURL;
link.download = 'image.png';
link.click();

// Revoke the temporary URL when done (optional)
URL.revokeObjectURL(fileURL);
}, 'image/png');
});


Подробнее здесь: https://stackoverflow.com/questions/784 ... image-file
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Как получить информацию о файле .so, сгенерированном соответствующей библиотекой, в файле APK с помощью студии Android
    Anonymous » » в форуме Android
    0 Ответы
    19 Просмотры
    Последнее сообщение Anonymous
  • Переход для градиентного фона
    Гость » » в форуме CSS
    0 Ответы
    16 Просмотры
    Последнее сообщение Гость
  • Анимированное растяжение градиентного фона, как это исправить?
    Anonymous » » в форуме CSS
    0 Ответы
    22 Просмотры
    Последнее сообщение Anonymous
  • Не могу найти метод JavaScript в сгенерированном файле TypeScript
    Anonymous » » в форуме Jquery
    0 Ответы
    10 Просмотры
    Последнее сообщение Anonymous
  • Не могу найти метод JavaScript в сгенерированном файле TypeScript
    Anonymous » » в форуме Javascript
    0 Ответы
    7 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Jquery»