drawCapsuleWithImageAndText(text, imageUrl) {
// console.log(text, imageUrl, '>>>>>>>>>>>>>>>>>>')
// 创建一个离屏的 Canvas 来加载图片并测量文本宽度
const offscreenCanvas = document.createElement("canvas");
const ctxOffscreen = offscreenCanvas.getContext("2d");
// 假设图片的大小是固定的 30x30
const imageSize = 30;
// 加载图片
const image = new Image();
image.src = imageUrl;
return new Promise((resolve) => {
image.onload = function () {
// 测量文本的宽度
ctxOffscreen.font = "20px Arial"; // 你可以根据需要调整字体和大小
const textWidth = ctxOffscreen.measureText(text).width;
// 计算胶囊的总宽度和高度
// 胶囊的高度等于图片的高度(因为图片是固定的 30x30)
// 胶囊的宽度等于图片的宽度加上文本的宽度,再加上一些内边距
const capsuleWidth = imageSize + textWidth + 30; // 20 是左右内边距的总和
const capsuleHeight = imageSize;
// 创建一个新的 Canvas 来绘制胶囊
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
canvas.width = capsuleWidth + 2;
canvas.height = capsuleHeight + 2;
// 绘制胶囊的轮廓(这里使用简单的圆角矩形来模拟胶囊形状)
const borderRadius = 15; // 圆角半径可以设置为高度的一半以实现半圆形效果
ctx.beginPath();
ctx.moveTo(borderRadius, 0);
ctx.lineTo(capsuleWidth - borderRadius, 0);
ctx.arc(capsuleWidth - borderRadius, capsuleHeight / 2, borderRadius, [(Math.PI) / 180] * (-90), [(Math.PI) / 180] * 90);
ctx.lineTo(borderRadius, capsuleHeight);
ctx.arc(borderRadius, capsuleHeight / 2, borderRadius, [(Math.PI) / 180] * 90, [(Math.PI) / 180] * (-90))
ctx.stroke();
ctx.fillStyle = 'skyblue'
ctx.fill();
ctx.closePath();
// 设置边框颜色并描边
ctx.font = "20px Arial"; // 你可以根据需要调整字体和大小
// ctx.strokeStyle = "#000";
// ctx.lineWidth = 2;
// ctx.stroke();
// // 填充背景颜色(可选)
// ctx.fillStyle = "#f0f0f0"; // 浅灰色背景
// ctx.fill();
// 绘制图片
ctx.drawImage(image, 10, (capsuleHeight - imageSize) / 2, 30, 30); // 10 是左内边距
// 绘制文本
ctx.fillStyle = "red"; // 黑色文本
ctx.textAlign = "left";
ctx.textBaseline = "bottom";
ctx.fillText(
text,
50,
25
);
// 注意:上面的文本垂直居中计算可能需要根据实际字体调整,这里是一个简化的示例
// 为了简化,我们直接将 Canvas 转换为 Base64 数据 URL 并打印到控制台(你可以根据需要处理它)
const base64Image = canvas.toDataURL("image/png");
// console.log(base64Image, 'base64Image');
resolve(base64Image);
// 如果你想要将这个 Canvas 添加到 DOM 中,可以这样做:
// document.body.appendChild(canvas);
// return image;
};
})
// 注意:由于图片是异步加载的,因此上面的代码在图片加载完成后才会执行绘制操作。
},
以上代码作为案例,传入一个文字和一张图片,生成一张新的图片,且生成图片的大小跟文字的长短有关,最终转换为base64格式,并用promise包裹返回。
let newImage = this.drawCapsuleWithImageAndText(item.total, require('@/assets/jiankong.png'));
// console.log(newImage, 'newImage')
newImage.then(res => {})
以上是调用方式,res即为base64图片地址。