2013-10-22 17 views
5

在HTML5畫布中,您可以將圖像作爲一個整體進行繪製,或者僅繪製其中的一部分,或僅將其中的一部分繪製到任意矩形(可能會縮放)。像在HTML Canvas或CSS中一樣定義SVG的源矩形<image>

下面是三個的例子:

enter image description here

這裏是用來繪製這三個例子的代碼:

ctx.drawImage(img, 0, 0); 

ctx.drawImage(img, 
       // source rect 
       50, 50, 70, 70, 
       // destination rect 
       0, 200, 70, 70 
      ); 

ctx.drawImage(img, 
       // source rect 
       50, 50, 70, 70, 
       // destination rect 
       0, 270, 30, 30 
      ); 

這也比較容易在CSS做。

我的問題是,對於給定的圖像,如何使用SVG <image>元素獲得相同的效果?

例如,我如何製作佔用50x50像素的圖像,該圖像顯示了參考href的一部分,就像在第一次剪裁中一樣?

可以使用剪切路徑剪切圖像的一部分,但是您(看起來)不能使用較大圖像的剪切路徑,同時將元素的寬度和高度定義爲很小。

下面是與上面的代碼加樣本SVG元素的小提琴:

http://jsfiddle.net/wcjVd/

回答

9

你並不需要一個clipPath可言,你可以使用viewBox做你想做什麼

<svg width="70px" height="70px" viewBox="50 50 70 70">  
    <image x="0" y="0" width="200" height="200" 
     xlink:href="http://placekitten.com/200/200" clip-path="url(#myClip)"> 
    </image> 
</svg> 

viewBox屬性的值是四個數字的列表<min-x>,<min-y><width><height>,用空格和/或逗號分隔,在用戶空間中指定一個矩形,該矩形應映射到由給定元素建立的視口的邊界,並考慮屬性preserveAspectRatio

Demo Here

很高興我可以幫助你在這裏,因爲你用帆布項目在幾個月前幫我!

編輯

你說,你需要的也改造他們,所以一個小時後,我來到了這幾個選項:

如果你能,改造原有的形象,做同樣的效果。Demo here如果你是在原點(0,0)想裁剪後的圖像,則代碼看起來像

<defs> 
    <clipPath id="myClip"> 
     <rect x="0" y="0" width="70" height="70"/> 
    </clipPath> 
</defs> 
    <image x="-50" y="-50" width="200" height="200" clip-path="url(#myClip)" 
      xlink:href="http://placekitten.com/200/200"></image> 

OR,更滿意,你可以用做一個use

<defs> <!-- Your original clip --> 
    <clipPath id="myClip"> 
     <rect x="50" y="50" width="70" height="70"/> 
    </clipPath>   
</defs> 
<image id="myImage" x="0" y="0" width="200" height="200" 
     xlink:href="http://placekitten.com/200/200" clip-path="url(#myClip)" /> 

<!-- Hide the original (I made a layer of white) --> 
<!-- This is the part that you could probably find a better way of doing --> 
<rect x="0" y="0" width="200" height="200" style="fill:white" /> 

<!-- Create what you want how you want where you want it --> 
<use x="-50" y="-50" width="200" height="200" xlink:href="#myImage" transform="scale(1.3)"/> 
</svg> 

Demo for that approach here

+0

謝謝扎克!這對我的情況不起作用(我也需要對它們進行轉換),但它是一個非常優雅的解決方案,可能是大多數人在Stackoverflow上尋找此Q所需要的,所以我將其標記爲接受。 –

+0

@SimonSarris我用一些其他選項更新了我的答案,您可以使用其他選項 –

+0

我最終得到的廣義解決方案涉及到clipPath + 3變換,您可以在此處看到一個示例:http:// jsfiddle。 net/rn7Ky/ –