如何将作为img标签src的SVG适配宽高并解决文本溢出裁剪问题
解决方案
最优方案:溢出文本末尾显示省略号
裁剪问题核心是两个配置缺失:一是SVG未配置自适应容器的视图属性,二是文本标签未配置溢出截断规则。修改后的完整代码如下:
修改后的JS代码
var text = 'It is a long <b>established fact</b> that a reader will be distracted by the <i>readable content of a page when looking</i> at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using Content here, content here, making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for lorem ipsum will uncover many web sites still in their infancy.'; var divCss = { 'display': 'flex', 'align-items': 'center', 'justify-content': 'center', 'margin': 'auto', 'height': '100%', 'width': '100%', 'box-sizing': 'border-box', 'padding': '8px' }; // 调整p标签样式,新增溢出截断规则 var paraCss = { 'text-align': 'center', 'font-size': '12px', 'margin': 0, 'overflow': 'hidden', 'text-overflow': 'ellipsis', 'display': '-webkit-box', '-webkit-line-clamp': '4', // 可自行调整最多展示的行数 '-webkit-box-orient': 'vertical', 'line-height': '1.5' }; var svgQ = document.createElementNS("http://www.w3.org/2000/svg", "svg"); // 给SVG新增自适应必要属性 svgQ.setAttributeNS(null, "id", "QId"); svgQ.setAttributeNS(null, "viewBox", "0 0 150 100"); // 宽高和img默认尺寸一致即可 svgQ.setAttributeNS(null, "preserveAspectRatio", "xMidYMid meet"); svgQ.setAttributeNS(null, "width", "100%"); svgQ.setAttributeNS(null, "height", "100%"); var txtElemQ = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject"); txtElemQ.setAttributeNS(null, "x", 0); txtElemQ.setAttributeNS(null, "y", 0); txtElemQ.setAttributeNS(null, "height", "100%"); txtElemQ.setAttributeNS(null, "width", "100%"); var divQ = txtElemQ.appendChild(document.createElement('div')); // 给内部div加XML命名空间,避免部分浏览器解析SVG时报错 divQ.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml'); $(divQ).css(divCss); var paraQ = divQ.appendChild(document.createElement('p')); $(paraQ).css(paraCss); paraQ.innerHTML = text; svgQ.appendChild(txtElemQ); var Q = new XMLSerializer().serializeToString(svgQ) var base64 = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent((Q)))); $('img').attr('src', base64);
CSS代码
img { height: 100px; width: 150px; border: 1px solid; /* 可手动拖拽调整img尺寸测试适配效果 */ resize: both; overflow: hidden; }
HTML代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <img src />
次优方案:压缩内容适配容器宽度
如果不需要保留字体大小统一,可通过动态缩放文本实现适配,只需修改paraCss新增缩放规则即可:
var paraCss = { 'text-align': 'center', 'font-size': '12px', 'margin': 0, 'width': '100%', 'white-space': 'nowrap', 'transform-origin': 'center top', 'transform': 'scale(0.8)' // 可根据容器宽度动态计算缩放比例 };
如需完全适配任意尺寸,可在生成SVG前先计算文本实际宽度,和容器宽度对比后动态设置scale的数值即可。
内容的提问来源于stack exchange,提问作者Mangrio
相关产品推荐
相关产品推荐

