2016-12-31 111 views
1

讓假設我有尺寸1280x720縮放比,沒有jQuery的調整大小圖像的SVG

的形象我不得不在上面繪製的是由在需要原始大小的圖像的頂部的服務器計算的一些多邊形這張圖片。他們是

<polygon points="531,243,687,316,663,593,360,717,191,520" />          
<polygon points="275,17,422,45,412,312,271,235" /> 
<polygon points="929,180,1108,248,985,707,847,676" /> 
<polygon points="598,70,700,101,658,531,516,436" /> 

現在我需要顯示圖像和覆蓋這些多邊形的頂部。然而,問題在於,圖像是由瀏覽器根據窗口大小動態調整的。圖像使用object-fit-contain CSS顯示,因此尺寸隨着調整大小而改變。

如何確保SVG協調上述自動縮放?

我已閱讀關於viewBox,但我真的沒有在這裏指定我自己的座標。問題是我真的不知道圖像將如何顯示/瀏覽器的大小,因爲它取決於窗口。

謝謝

回答

1

SVG的默認縮放行爲與object-fit: contain相同。因此,您只需將SVG的viewBox寬度和高度設置爲與圖像相同的尺寸即可。

因此,例如,如果您的圖像是640x480,請將您的viewBox設置爲"0 0 640 480"

div { 
 
    position: relative; 
 
} 
 

 
div > img, 
 
div > svg { 
 
    width: 100%; 
 
    height: 200px; 
 
} 
 

 
img { 
 
    object-fit: contain; 
 
} 
 

 
svg { 
 
    position: absolute; 
 
    top: 0; 
 
}
<div> 
 
    <img src="http://lorempixel.com/output/people-q-c-640-480-1.jpg"/> 
 
    
 
    <svg viewBox="0 0 640 480"> 
 
    <circle cx="450" cy="215" r="40" fill="none" stroke="red" stroke-width="10"/> 
 
    </svg> 
 
</div>

+0

Paul謝謝,我發佈了在另一個問題中使用viewBox的問題細節,因爲這個問題沒有有所有的細節 - 讓我知道如果我應該只是編輯這個問題http://stackoverflow.com/questions/41416484/is-svg-resizing-this-hard-what-am--missing – user1361529

0

你能避免以任何方式用html做到這一點嗎?一個簡單的圖像編輯器似乎是一個更好的方法,但我不能說,因爲我不知道你的情況。否則,您可能可以使用保證金進行展示位置。

+0

可惜不是,img標籤是現場攝像機飼料服務器發送不斷變化。我需要在它的頂部顯示「警報區域」,這是多邊形(這些數據也來自服務器通過API) – user1361529

0

您可以使用<svg>標籤內<image>元素,那麼他們將成爲一個,你可以做任何規模的吧。

下面是一個SVG圖像例如:

<svg xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink"> 

    <rect x="10" y="10" height="130" width="500" style="fill: #000000"/> 

    <image x="20" y="20" width="300" height="80" 
    xlink:href="http://jenkov.com/images/layout/top-bar-logo.png" /> 

    <line x1="25" y1="80" x2="350" y2="80" 
      style="stroke: #ffffff; stroke-width: 3;"/> 
</svg> 

參考:SVG image element