像在HTML Canvas或CSS中一样,为SVG <image>定义源矩形

Sim*_*ris 5 html css svg canvas

在HTML5 Canvas中,您可以将图像作为一个整体绘制,或者只绘制一部分图像,或者只将一部分绘制到任意矩形(可以缩放它).

以下是这三个例子:

在此输入图像描述

以下是用于绘制这三个示例的代码:

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
             );
Run Code Online (Sandbox Code Playgroud)

这在CSS中也相对容易.

我的问题是,对于给定的图像,如何使用SVG <image>元素实现相同的效果?

例如,我如何制作一个占据50x50像素的图像,它显示了参考href的一部分,就像在第一个作物中一样?

可以使用剪切路径来裁剪图像的一部分,但是然后您(看似)不能使用较大图像的剪切路径,同时将<image>元素的宽度和高度定义为较小.

这里是上面的代码和一个示例SVG元素的小提琴:

http://jsfiddle.net/wcjVd/

Zac*_*ier 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>
Run Code Online (Sandbox Code Playgroud)

所述的值viewBox属性是四个数字的列表<min-x>,<min-y>,<width><height>,由空格和/或逗号,其指定在其中应被映射到由给定元素建立的视口的边界用户空间中的矩形分隔,同时考虑到属性preserveAspectRatio.

在这里演示

很高兴我能在这里帮到你,因为几个月前你帮我做了一个Canvas项目!

编辑

你说你也需要改造它们,所以一小时后我想出了这些几种选择:

如果可以,请转换原始图像并执行相同的效果.在这里进行演示如果您想要在原点处裁剪图像,(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>
Run Code Online (Sandbox Code Playgroud)

或者,更令人满意的是,你可以使用一个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>
Run Code Online (Sandbox Code Playgroud)

在这里演示这种方法