簡體   English   中英

如何將 svg 數據作為 src 擬合/剪輯到圖像的寬度和高度

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

我可以讓這個 SVG 源適合我的圖像寬度和高度變化。 當寬度和高度增加時,它會自動調整線條,但在減少的情況下,文本將被剪裁如下代碼。

JSFiddle

對我來說,最好的解決方案是僅將文本顯示為尺寸並在最后添加省略號 (...),或者第二個可能是通過壓縮原始寬度來適應數據的解決方法。

 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 />

當邊界框大小發生變化時,您必須重新繪制 svg 圖像。 為此,可以向 window object 添加一個偵聽器,並且每當調整 window 的大小時,再次調用繪圖 ZC1C425268E68385D1AB504。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM