<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>多文字图片生成</title>
</head>
<body>
<script>
function addTextsToImageAndDownload(config) {
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = 'Anonymous';
img.src = config.imagePath;
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
// 绘制所有文字
config.texts.forEach(textConfig => {
// 设置文字样式
ctx.font = `${textConfig.fontSize || '30px'} ${textConfig.fontFamily || 'Arial'}`;
ctx.fillStyle = textConfig.color || '#000';
ctx.textBaseline = textConfig.textBaseline || 'top';
// 绘制文字
ctx.fillText(
textConfig.content,
textConfig.x || 10,
textConfig.y || 10
);
});
// 生成下载链接
canvas.toBlob(blob => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = config.filename || 'new_image.png';
a.click();
URL.revokeObjectURL(url);
resolve();
}, config.mimeType || 'image/png');
};
img.onerror = () => {
reject(new Error('图片加载失败'));
};
});
}
// 示例调用
const config = {
imagePath: 'https://example.com/sample.jpg', // 替换为实际图片路径
texts: [
{
content: '标题',
x: 50,
y: 50,
color: '#0000ff',
fontSize: '40px',
fontFamily: '黑体'
},
{
content: '副标题',
x: 50,
y: 100,
color: '#ff00ff',
fontSize: '24px',
textBaseline: 'middle'
},
{
content: '右下角签名',
x: 300,
y: 400,
color: '#888',
fontSize: '18px'
}
],
filename: 'custom_image.png',
mimeType: 'image/png'
};
addTextsToImageAndDownload(config)
.then(() => console.log('下载完成'))
.catch(err => console.error(err));
</script>
</body>
</html>
主要修改说明:
-
参数结构调整:
- 接收一个配置对象,包含
imagePath
(图片路径)、texts
(文字数组)、filename
(下载文件名)和mimeType
(图片格式)。
- 接收一个配置对象,包含
-
文字配置项:
- 每个文字对象支持以下属性:
{ content: '文字内容', // 必选 x: 10, // X坐标(默认10) y: 10, // Y坐标(默认10) color: '#000', // 颜色(默认黑色) fontSize: '30px', // 字体大小(默认30px) fontFamily: 'Arial', // 字体(默认Arial) textBaseline: 'top' // 文字基线(默认top) }
- 每个文字对象支持以下属性:
-
循环绘制文字:
- 使用
forEach
遍历所有文字配置 - 动态设置每个文字的样式
- 支持不同的文字基线(top/middle/bottom等)
- 使用
-
增强功能:
- 支持自定义下载文件名
- 支持多种图片格式(png/jpeg等)
- 处理跨域图片加载
- 更友好的错误处理
使用示例:
const config = {
imagePath: 'https://example.com/background.jpg',
texts: [
{ content: '左上角文字', x: 20, y: 20, color: '#ff0000' },
{ content: '居中文字', x: 200, y: 200, textBaseline: 'middle' },
{ content: '右下角文字', x: 400, y: 400, fontSize: '16px' }
]
};
addTextsToImageAndDownload(config);