用svg的text
標籤文字換行難控制
在foreignObject
標籤裏能夠寫html, 而且用css控制文字換行,使用前在caniuse裏查看是否適配所用瀏覽器
基本格式
<foreignObject width="100" height="200">
<div style="display:flex;justify-content:center;align-items:center;.........">xxxxxx</div>
</foreignObject>
js動態代碼
const width = 200,
height = 150,
html = `123465789`;
const NS = 'http://www.w3.org/2000/svg';
const foreignObject = document.createElementNS(NS, 'foreignObject');
foreignObject.setAttribute('width', width);
foreignObject.setAttribute('height', height);
foreignObject.innerHTML = `<div xmlns="${NS}" style="width:100%;height:100%;font-size:12px;padding:0 8px;color:#fff;display:flex;justify-content:center;align-items:center;line-height: 12px;">${html}</div>`;