如何創建一個框(rect?),使用SVG將其自身調整爲適合其內部的文本?如何在SVG文本框中繪製一個框?
回答
對不起,這個答案花了我很長時間,但我正在學習如何使用ECMAScript和XML DOM。
好的。因此,假設你有你的文檔結構如下所示:
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.1"
width="800"
height="600"
id="example_text">
<g id="layer1">
<text
x="123.4"
y="567.8"
id="text_holder">
<tspan id="tspan1">Text</tspan>
<tspan id="tspan2">More text</tspan>
</text>
</g>
<script type="text/ecmascript">
function create_from_rect (client_rect, offset_px) {
if (! offset_px) {offset_px=0;}
var box = document.createElementNS(
document.rootElement.namespaceURI,
'rect'
);
if (client_rect) {
box.setAttribute('x', client_rect.left - offset_px);
box.setAttribute('y', client_rect.top - offset_px);
box.setAttribute('width', client_rect.width + offset_px * 2);
box.setAttribute('height', client_rect.height + offset_px * 2);
}
return box;
}
function add_bounding_box (text_id, padding) {
var text_elem = document.getElementById(text_id);
if (text_elem) {
var f = text_elem.getClientRects();
if (f) {
var bbox = create_from_rect(f[0], padding);
bbox.setAttribute(
'style',
'fill: none;'+
'stroke: black;'+
'stroke-width: 0.5px;'
);
text_elem.parentNode.appendChild(bbox);
}
}
}
add_bounding_box('text_holder', 5);
</script>
</svg>
在根<svg>
元素使得它的創建DOM結構上面後執行,就像JavaScript的Web頁面上的底部添加<script>
標籤。
謝謝,我對你的回答印象非常深刻。它比我預期的要做得更多。 – 2010-06-21 22:25:16
我應該補充一點,我在Firefox中顯示時嘗試過這種方式,但它在Chrome中無法正常工作。 – amphetamachine 2010-06-24 06:22:19
以下方法會使事情變得更簡單嗎?
var text_elem = document.getElementById(text_id);
var bbox = text_elem.getBBox();
然後用bbox的寬度和高度來畫一個矩形?
你能解釋一下如何使它更簡單嗎?我將如何使用您提供的代碼? – 2012-04-19 20:34:22
除非我沒有正確理解你,否則你所要做的就是圍繞文本繪製一個矩形,所以只需從文本元素的x,y開始繪製矩形,並使用bbox的寬度和高度繪製矩形。我沒有測試過這些代碼,但是我猜測,檢查bbox不爲空是沒有必要的。 當我說我的方法會簡化事情時,我過於樂觀;它會,但不會顯着 – JamieJag 2012-04-20 22:31:46
- 1. 繪製文本框中
- 2. 在WinRT中繪製一個SVG文件
- 3. 在文本框中繪製形狀
- 4. 在文本框中繪製空白
- 5. 如何定位一個文本框下一個SVG元素?
- 6. GWT繪製文本框
- 7. 在java中繪製一個簡單的文本框?
- 8. 如何繪製一個窗口框架
- 9. Javascript如何將多個文本框複製到一個文本框中
- 10. 在每個文本框內繪製一個矩形c#winform
- 11. 如何在一個文本框中
- 12. 如何在一個框架中繪製2個正態分佈?
- 13. 在沒有WPF的擴展玻璃框中繪製文本框
- 14. 如何從文本框中選一個文本框
- 15. 如何在c中的圖片框頂部繪製可編輯的文本框
- 16. 如何在文本區域中使用鼠標選擇文本時圍繞文本繪製一個框?
- 17. 如何在php中用虛線邊框繪製一個圓圈?
- 18. 如何在R中的圖例周圍繪製一個框?
- 19. 數據綁定多個文本框在一個文本框中
- 20. 如何在java中繪製框圖?
- 21. 如何在圖像中繪製邊框?
- 22. 在GraphicsPath繪製的文本週圍繪製矩形邊框
- 23. 如何在一個文本框C#
- 24. C#WPF如何在一個文本框
- 25. 的iOS drawRect中繪製一個邊框
- 26. 繪製一個複選框在TListView的
- 27. opencv opengl繪製在一個框架
- 28. 如何在運行時繪製一條從文本框中間退出的線?
- 29. 如何在畫布內繪製文本框
- 30. 如何使用DynamicLayout和Ellipsize在畫布上繪製文本框
另請參閱:http://stackoverflow.com/questions/2938779/svg-scaling-text-to-fit-container – 2012-08-04 17:32:45
該問題中提到的視口屬性與此處的答案無關。 – 2012-12-31 20:08:13
bbox的好例子https://bl.ocks.org/mbostock/1160929 – marioosh 2017-11-16 08:43:17