小编典典

角度和SVG滤镜

angularjs

当将SVG与AngularJS一起使用时,我遇到了一个奇怪的行为。我正在使用该$routeProvider服务配置我的路线。当我将这个简单的SVG放在模板中时,一切都很好:

<div id="my-template">
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
        <rect fill="red" height="200" width="300" />
    </svg>
    // ...
</div>

但是,当我添加一个过滤器时,例如使用以下代码:

<div id="my-template">
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
        <defs>
            <filter id="blurred">
                <feGaussianBlur stdDeviation="5"/>
            </filter>
        </defs>
        <rect style="filter:url(#blurred)" fill="red" height="200" width="300" />
    </svg>
</div>

然后:

  • 它可以在我的 主页上运行
  • 使用 Firefox时 ,SVG 在其他页面 上不再可见,但是仍然留有空间。使用 Chrome时 ,SVG可见,但完全不模糊。
  • 当我手动(使用Firebug)删除filter样式时,SVG再次可见。

这是路由配置:

$routeProvider
    .when('/site/other-page/', {
            templateUrl : 'view/Site/OtherPage.html',
            controller : 'Site.OtherPage'
    })
    .when('/', {
            templateUrl : 'view/Site/Home.html',
            controller : 'Site.Home'
    })
    .otherwise({
        redirectTo : '/'
    })
;

[Fiddle](http://jsfiddle.net/Blackhole/chehd/2/)

请注意,尽管Chrome可在Firefox中“运行”,但我无法在Fiddle中重现该问题。

我尝试使用来创建我的整个SVG都无济于事document.createElementNS()

有人对正在发生的事情有想法吗?


阅读 240

收藏
2020-07-04

共1个答案

小编典典

问题

问题是<base>我的HTML页面中有一个标签。因此,用于标识过滤器的IRI不再相对于当前页面,而是相对于<base>标记中指示的URL

例如,此URL也是我主页的URL http://example.com/my-folder/

对于除主页之外的网页,http://example.com/my-folder/site/other- page/例如,#blurred在计算绝对URL http://example.com/my- folder/#blurred。但是对于一个简单的GET请求,没有JavaScript,因此也没有AngularJS,这只是我的基本页面,没有加载模板。因此,
该页* 面上 不存在#blurred过滤器。 *

在这种情况下, Firefox 不会呈现<rect>(这是正常行为,请参阅W3Crecommandation)。Chrome 根本不应用过滤器。

对于主页,#blurred还将计算为绝对URLhttp://example.com/my-folder/#blurred。但是这次,这也是当前的URL。无需发送GET请求,因此 存在*#blurred过滤器。 *

我应该已经看到了对的额外请求http://example.com/my-folder/,但是为了防御起见,它在对JavaScript文件的大量其他请求中丢失了。

解决方案

如果<base>标记是强制​​性的,则解决方案是使用绝对IRI标识过滤器。在AngularJS的帮助下,这非常简单。在控制器或链接到SVG的指令中,注入$location服务并使用absUrl()getter:

$scope.absUrl = $location.absUrl();

现在,在SVG中,只需使用以下属性:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <defs>
        <filter id="blurred">
            <feGaussianBlur stdDeviation="5"/>
        </filter>
    </defs>
    <rect style="filter:url({{absUrl}}#blurred)" fill="red" height="200" width="300" />
</svg>

2020-07-04