简体   繁体   English

如何将 svg 数据作为 src 拟合/剪辑到图像的宽度和高度

[英]How to fit / clip svg data as src to image to its width and height

Ho can I make this SVG source fit as my image width and height change.我可以让这个 SVG 源适合我的图像宽度和高度变化。 It automatically adjusts the lines when width and height increase, but in case of a decrease, the text is clipped as below code.当宽度和高度增加时,它会自动调整线条,但在减少的情况下,文本将被剪裁如下代码。

JSFiddle JSFiddle

For me, the best solution would be to just display the text as of dimensions and add an ellipsis (...) in the end or the second may be a workaround to just fit the data by squeezing its original width.对我来说,最好的解决方案是仅将文本显示为尺寸并在最后添加省略号 (...),或者第二个可能是通过压缩原始宽度来适应数据的解决方法。

 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%' }; var paraCss = { 'text-align': 'center', 'font-size': '12px', 'padding': '8px' }; var svgQ = document.createElementNS("http://www.w3.org/2000/svg", "svg"); svgQ.setAttributeNS(null, "id", "QId"); 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')); $(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);
 img { height: 100px; width: 150px; border: 1px solid; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <img src />

You will have to redraw the svg image when bounding box size changes.当边界框大小发生变化时,您必须重新绘制 svg 图像。 To do this can add a listener to window object and whenever window is resized, call the draw function again.为此,可以向 window object 添加一个侦听器,并且每当调整 window 的大小时,再次调用绘图 ZC1C425268E68385D1AB504。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM