canvas:文字转图片

文章介绍了如何使用JavaScript的CanvasAPI将指定的文字转换为图片,以便在配合富文本编辑器时实现内容的动态生成和编辑。

需求:将某段文字通过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)
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值