在 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
);
这在 CSS 中也相对容易做到。
我的问题是,对于给定的图像,如何使用 SVG 实现相同的效果 <image>
元素?
例如,我如何制作一个占据 50x50 像素的图像,显示引用 href 的一部分,就像在第一次裁剪中一样?
可以使用剪切路径来裁剪部分图像,但是您(貌似)不能在定义 <image>
的宽度和高度时使用较大图像的剪切路径。元素要小。
这是一个包含上述代码和示例 SVG 元素的 fiddle :
最佳答案
你不需要 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>
The value of the
viewBox
attribute is a list of four numbers<min-x>
,<min-y>
,<width>
and<height>
, separated by whitespace and/or a comma, which specify a rectangle in user space which should be mapped to the bounds of the viewport established by the given element, taking into account attributepreserveAspectRatio
.
很高兴我能在这里帮助你,因为几个月前你帮助我完成了一个 Canvas 元素!
编辑
你说你也需要转换它们,所以一个小时后我想出了以下几个选项:
如果可以的话,对原图进行变换,做同样的效果。 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>
或者,更令人满意的是,您可以使用 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>
关于html - 像在 HTML Canvas 或 CSS 中一样为 SVG <image> 定义源矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19525827/