t-comm
Version:
专业、稳定、纯粹的工具库
81 lines (78 loc) • 2.53 kB
JavaScript
import { b as __awaiter, c as __generator } from '../tslib.es6-096fffdd.js';
import { getCanvas } from './get-canvas.mjs';
/**
* 为图片增加文字
*
* @param {Object} config 配置
* @param {number} config.width 宽度
* @param {number} config.height 高度
* @param {Array<string>} config.textList 文字列表,支持多行
* @param {string} config.imgPath 图片路径
* @returns {string} canvas.toDataURL生成的base64图片
*
* @example
*
* ```ts
* const imgUrl = addTextForImg({
* width: 300,
* height: 300,
* textList: ['第一行', '第二行'],
* imgPath: './test.png',
* })
* ```
*/
function addTextForImg(_a) {
var width = _a.width,
height = _a.height,
textList = _a.textList,
imgPath = _a.imgPath;
return __awaiter(this, void 0, void 0, function () {
function drawBackground() {
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function fillTitle(textList) {
ctx.lineWidth = 1;
ctx.strokeStyle = '#ccc';
ctx.textAlign = 'start';
ctx.font = '10px Arial';
ctx.fillStyle = '#000';
for (var j = 0; j < textList.length; j++) {
ctx.fillText(textList[j], 15, 20 + j * lineHeight);
}
}
var canvasLibrary, sizeOf, createCanvas, loadImage, image, lineHeight, dpr, topHeight, dimensions, oHeight, oWidth, canvas, ctx, imgUrl;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
canvasLibrary = getCanvas();
if (!canvasLibrary) return [2 /*return*/, ''];
sizeOf = require('image-size');
createCanvas = canvasLibrary.createCanvas, loadImage = canvasLibrary.loadImage;
return [4 /*yield*/, loadImage(imgPath)];
case 1:
image = _b.sent();
lineHeight = 15;
dpr = 2;
topHeight = textList.length * lineHeight + 15;
dimensions = sizeOf(imgPath);
oHeight = dimensions.height, oWidth = dimensions.width;
if (!width) {
width = oWidth;
}
if (!height) {
height = oHeight;
}
canvas = createCanvas(width * dpr, (height + topHeight) * dpr);
ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr);
drawBackground();
ctx.drawImage(image, 0, topHeight, width, width);
fillTitle(textList);
imgUrl = canvas.toDataURL();
return [2 /*return*/, imgUrl];
}
});
});
}
export { addTextForImg };