使用feDisplacementMap+feImage滤镜实现水波纹效果(计算动态值)

2022-07-29,,,,

该文章已经讲的特别细致了,该篇仅以此记录动效过程中各点的计算

1.fedisplacementmap

fedisplacementmap 实际上是一个位置替换滤镜,就是改变元素和图形的像素位置的。遍历原图形的所有像素点,使用fedisplacementmap重新映射替换一个新的位置,形成一个新的图形。fedisplacementmap滤镜在业界的主流应用是对图形进行形变,扭曲,液化。

p'(x,y) ← p( x + scale * (xc(x,y) - 0.5), y + scale * (yc(x,y) - 0.5))

· p'(x,y)指的是转换之后的x, y坐标。
· x + scale * (xc(x,y) - 0.5), y + scale * (yc(x,y) - 0.5)指的是具体的转换规则。
· xc(x,y)表示当前x,y坐标像素点其x轴方向上设置的对应通道的计算值,范围是0~1。
· yc(x,y)表示当前x,y坐标像素点其y轴方向上设置的对应通道的计算值,范围是0~1。
· -0.5是偏移值,因此xc(x,y) - 0.5范围是-0.5~0.5yc(x,y) - 0.5范围也是-0.5~0.5
· scale表示计算后的偏移值相乘的比例,scale越大,则偏移越大。

再用一句话解释就是,根据设定的通道颜色对原图的x, y坐标进行偏移。

默认值 取值 说明
xchannelselector a a or r or g or b 对应xc(x,y),表示x轴坐标使用的是哪个颜色通道进行位置偏移
ychannelselector a a or r or g or b 对应yc(x,y),表示y轴坐标使用的是哪个颜色通道进行位置偏移
color-interpolation-filters linearrgb linearrgb or srgb 滤镜对颜色进行计算时候采用的颜色模式类型
scale 0 可正可负 缩放比例 通常使用正数值处理,值越大,偏移越大。
in sourcegraphic sourcegraphic,sourcealpha,backgroundimage, backgroundalpha,fillpaint,strokepaint,以及自定义的滤镜的原始引用 原始图形
in2 元素的result属性值 同in 用来映射的图形

2.通过fedisplacementmap和feimage实现水波特效

实现水波效果通常使用下图

<svg id='svg' width="400" height="400" xmlns="http://www.w3.org/2000/svg">
    <defs>
        <filter id="filter-ripple" primitiveunits='objectboundingbox'>
            <feimage id='feimage' result="pict2" xlink:href="上述图片地址"  x="0" y="0" width="100%" height="100%"></feimage>
            <fedisplacementmap id='displacement-map' result='ok' scale="0" xchannelselector="r" ychannelselector="g" in2="pict2" in="sourcegraphic" color-interpolation-filters="srgb"></fedisplacementmap>
            <fecomposite operator="in" in2="pict2"></fecomposite>
            <fecomposite in2="sourcegraphic"></fecomposite> //这个的目的是因为添加滤镜的元素可见区域和feimage元素的大小一致。融合原有元素保证整个元素都可见
        </filter>
    </defs>
</svg>

水波特效,是通过<feimage>标签 x,y,width,height四个属性和<fedisplacementmap>标签scale动态变化实现。
就像涟漪,以石子掉落处为中心,范围由小扩大,起伏由强减弱。 转为代码,也就是width,height由小变大,scale由大变小
根据点击事件,可以计算出中心坐标(pointx,pointy)

在扩散过程中,中心坐标不变,x,y为图片的起始坐标
pointx = width/2 + x ;pointy = height/2 + y => x = pointx - width/2; y = pointy - height/2
width,height,scale的最大值就可以根据需求来设置啦~

参考资料

https://www.zhangxinxu.com/wordpress/2017/12/understand-svg-fedisplacementmap-filter/

到此这篇关于使用fedisplacementmap+feimage滤镜实现水波纹效果(计算动态值)的文章就介绍到这了,更多相关fedisplacementmap滤镜水波纹内容请搜索以前的文章或继续浏览下面的相关文章,希望大家以后多多支持!

《使用feDisplacementMap+feImage滤镜实现水波纹效果(计算动态值).doc》

下载本文的Word格式文档,以方便收藏与打印。