2014-03-25 38 views
3

我完全被SVG圖像困惑。我想將圖像裁剪爲其核心內容。我想通過指定其視框和/或視口和/或其他任何東西來裁剪它,除非我不想更改折線元素中的任何點。圖像是呈現這樣的東西。 (注:邊框僅用於說明目的。邊界實際上不是SVG的一部分。)裁剪SVG的正確方法?

original

,我想,所以它看起來像這樣的東西裁剪。 (注:再次邊境僅用於說明目的)

cropped

鑑於這種SVG XML如何剪裁呢?

<?xml version="1.0" encoding="utf-8"?> 
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" > 
    <polyline points="39,340 42,338 47,333 54,322 68,308 83,292 91,277 100,259 106" style="fill:none;stroke:black;stroke-width:3"/> 
    <polyline points="71,299 82,303 95,304 109,302 120,301" style="fill:none;stroke:black;stroke-width:3"/> 
    <polyline points="212,275 228,254 233,233 240,208 239,246 188,278 174,306 158,334 149,351 144,358 140,362 139,362 139,340 179,313 186" style="fill:none;stroke:black;stroke-width:3"/> 
    <polyline points="169,345 174,347 227,333 231,330 330,371 328,374 414,209 410,192 404,183 401,177 398,177 395,179 379,340 385,384 397,414" style="fill:none;stroke:black;stroke-width:3"/> 
</svg> 
+0

你怎麼想裁剪。你有什麼嘗試?你卡在哪裏? – PeeHaa

+0

我已經嘗試將視口設置爲各種高度,寬度值,並很快發現單獨無法工作。我還嘗試將viewbox設置爲許多不同的值,並取得了一些成功。我發現關閉viewBox =「39 243 378 417」,但我不是100%確定爲什麼那種有點接近。我還查看了preserveAspectRatio屬性的各種排列,並最終嘗試了上述所有內容的幾種組合。我只是失敗了。 – HairOfTheDog

回答

5

當SVG是inline,可以計算其使用getBBox()根SVG viewBox

以下是爲您的折線的例子:

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>Compute viewBox</title> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
</head> 
<body> 
<center> 
<h3>Compute viewBox</h3> 
<div id=svgDiv style='background-color:lightgreen'> 
<svg id=mySVG> 
    <polyline points="39,340 42,338 47,333 54,322 68,308 83,292 91,277 100,259" style="fill:none;stroke:black;stroke-width:3"/> 
    <polyline points="71,299 82,303 95,304 109,302 120,301" style="fill:none;stroke:black;stroke-width:3"/> 
    <polyline points="212,275 228,254 233,233 240,208 239,246 188,278 174,306 158,334 149,351 144,358 140,362 139,362 139,340 179,313 " style="fill:none;stroke:black;stroke-width:3"/> 
    <polyline points="169,345 174,347 227,333 231,330 330,371 328,374 414,209 410,192 404,183 401,177 398,177 395,179 379,340 385,384 397,414" style="fill:none;stroke:black;stroke-width:3"/> 
</svg> 
</div> 
<button onClick=fit()>fit</button> 
viewVox:<input type=text size=20 id=vbValue /> 
</center> 
</body> 
<script> 
//---button-- 
function fit() 
{ 
    var bb=mySVG.getBBox() 
    var bbx=bb.x 
    var bby=bb.y 
    var bbw=bb.width 
    var bbh=bb.height 
    var vb=[bbx,bby,bbw,bbh] 
    mySVG.setAttribute("viewBox", vb.join(" ")) 
    vbValue.value=vb.join(" ") 
    svgDiv.style.width=bbw+"px" 
    svgDiv.style.height=bbh+"px" 
} 
</script> 
</html> 
+0

我在Android上使用的SVG庫沒有getBBox方法。 (我假設BBox代表Bounding Box。)但是,您的示例HTML代碼完成了這個任務,因爲它向我展示了viewBox是一個標準的矩形結構,定義爲{x,y,width,height}。知道我能夠對每條折線的點進行一些簡單的計算來找到這四個值。 – HairOfTheDog