CSS: Blur and invert colors for entire page

给你一囗甜甜゛ 提交于 2019-12-06 01:22:58

You could use svg's foreignObject element to import the entire body's content into an svg element and then apply the filters on the foreignObject which will apply the filters on the entire body.

Browser support for svg filters vs CSS filters.

Demo on CodePen

html, body {
  width: 100%;
  height: 100%;
  background: #222222;
  margin: 0;
}
<body>
  <svg width="100%" height="100%" style="position: absolute; left:0;top: 0;">
    <defs>
      <filter id="blur-and-invert">
        <feGaussianBlur in="SourceGraphic" stdDeviation="3" />
        <feColorMatrix type="saturate" values="1" result="fbSourceGraphic" />
        <feColorMatrix in="fbSourceGraphic" values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0 " />
      </filter>
    </defs>
    <foreignObject width="100%" height="100%" filter="url(#blur-and-invert)">
      <!-- Here goes the content -->
      <img src="http://lorempixel.com/450/300/sports" width="100%" height="100%" />
    </foreignObject>
  </svg>
</body>

If you want to apply the filter on an event, you could remove the filter attribute from the foreignObject element initially and apply the filter using JavaScript this way.

var body = document.getElementsByTagName('foreignObject')[0];

body.setAttribute('filter', 'url(#blur-and-invert)')

var body = document.getElementsByTagName('foreignObject')[0];

body.setAttribute('filter', 'url(#blur-and-invert)')
html, body {
  width: 100%;
  height: 100%;
  background: #222222;
  margin: 0;
}
<body>
  <svg width="100%" height="100%" style="position: absolute; left:0;top: 0;">
    <defs>
      <filter id="blur-and-invert">
        <feGaussianBlur in="SourceGraphic" stdDeviation="3" />
        <feColorMatrix type="saturate" values="1" result="fbSourceGraphic" />
        <feColorMatrix in="fbSourceGraphic" values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0 " />
      </filter>
    </defs>
    <foreignObject width="100%" height="100%">
      <img src="http://lorempixel.com/450/300/sports" width="100%" height="100%" />
    </foreignObject>
  </svg>
</body>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!