需求:将某段文字通过canva转为一张图片,配合富文本编辑器可以实现特定内容的整体增删
封装的文字转图片方法:
// 文字转图片
export const txtToImg = (text, arg = {}) => {
let config = {
width: 0,
height: 0,
wPadding: 6,
hPadding: 4,
backgroundColor: 'transparent',
fontSize: 14,
fontFamily: 'sans-serif',
borderColor: '#00b853',
borderWidth: 1
}
config = {...config, ...arg};
let span = document.createElement("span")
span.style.display = 'inline-block'
span.style.fontSize = config.fontSize
span.style.fontFamily = config.fontFamily
span.innerText = text
document.body.append(span)
config.width = span.clientWidth + config.wPadding * 2;
config.height = config.fontSize + config.hPadding * 2;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = config.width;
canvas.height = config.height;
canvas.style.backgroundColor = config.backgroundColor;
ctx.font = `${config.fontSize}px/${config.fontSize}px ${config.fontFamily}`;
ctx.textBaseline = 'middle';
ctx.fillStyle = config.borderColor;
ctx.fillText(text, (config.width - ctx.measureText(text).width) / 2, config.fontSize / 2 + config.hPadding + config.borderWidth);
ctx.strokeStyle = config.borderColor;
ctx.lineWidth = config.borderWidth;
ctx.beginPath();
ctx.arc(config.height / 2, config.height / 2, config.height / 2 - config.borderWidth / 2, Math.PI * 3 / 2, Math.PI / 2, true);
ctx.lineTo(config.width - config.height / 2, config.height - config.borderWidth / 2);
ctx.arc(config.width - config.height / 2, config.height / 2, config.height / 2 - config.borderWidth / 2, -Math.PI * 3 / 2, -Math.PI / 2, true);
ctx.lineTo(config.height / 2, config.borderWidth / 2);
ctx.stroke();
ctx.closePath();
document.body.removeChild(span)
const imgData = ctx.getImageData(0, 0, config.width, canvas.height);
return canvas.toDataURL(imgData, 1)
}
文章介绍了如何使用JavaScript的CanvasAPI将指定的文字转换为图片,以便在配合富文本编辑器时实现内容的动态生成和编辑。
2101

被折叠的 条评论
为什么被折叠?



