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

标签 html css canvas svg

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

以下是这三者的示例:

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 的一部分,就像在第一次裁剪中一样?

可以使用剪切路径来裁剪部分图像,但是您(貌似)不能在定义 <image> 的宽度和高度时使用较大图像的剪切路径。元素要小。

这是一个包含上述代码和示例 SVG 元素的 fiddle :

http://jsfiddle.net/wcjVd/

最佳答案

你不需要 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 attribute preserveAspectRatio.

Demo Here

很高兴我能在这里帮助你,因为几个月前你帮助我完成了一个 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>

Demo for that approach here

关于html - 像在 HTML Canvas 或 CSS 中一样为 SVG <image> 定义源矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19525827/

相关文章:

javascript - var 在功能之外不受影响?

android - 我可以在 android canvas 上绘制 pi 使其看起来像是用 drawText 绘制的吗?

javascript - 停止换行提交表单?

html - 两列布局,其中主要内容 DIV 的宽度是可变的(使用所有可用空间 100%)

html - 媒体查询在 IE9 iframe 中失败

jquery - 这是对表格的有效使用吗?有更好的选择吗?

javascript - 控制程序生成方 block 的变异和衰减

javascript - 动态创建贝塞尔曲线?

php - 检查站点的首次访问

jquery - 导航栏和 bxslider 之间的随机空白