Я написал следующий код для создания файла изображения 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
Создание градиентного фона в файле изображения, сгенерированном JavaScript ⇐ Jquery
Программирование на jquery
1715322271
Anonymous
Я написал следующий код для создания файла изображения [b]PNG[/b], который печатает градиентный фон тела 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})`;
}
Он создает файл с именем [b]image.png[/b], но не открывается никаким инструментом!?
Мой цель состоит в том, чтобы просто создать файл [b].png[/b], который может отображать фон тела HTML, а именно:
body {
background-image : linear-gradient(0deg ,rgb(0,0,153), rgb(107,0,0));
}
[b]Изменить:[/b]
Моя главная цель — не отображать фон тела 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[i].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');
});
Подробнее здесь: [url]https://stackoverflow.com/questions/78457927/creating-a-gradient-background-in-a-javascript-generated-image-file[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия