1

因此,您可以通过执行以下操作在 CSS 中获得像素化:

  • 设置background-image为非常小的图像(例如 50 像素或 100 像素)。
  • 设置image-rendering: pixelated在元素上。

这会给你像素化的外观。

现在我想通过在浏览器完成下载后用大图像替换“非常小的图像”来制作动画:

let img = new Image()
img.src = largeVersion
img.onload = function(){
  // set css background-image to the new image perhaps, not sure...      
}

问题有两个方面。

  1. 我想要使background-image​​用background-size: cover它来正确填充容器元素。所以你不能在任何像素化动画中使用背景大小。
  2. transform: scale(0.1)(以接近原始像素化大小)不起作用,因为它会缩放整个元素。

我想做这样的事情:动画transform: scale(x)从 50px 像素化图像到 2000px 非像素化图像,超过 0.3 或 0.5 秒。但这不起作用。我想也许使用背景大小,但由于限制,这也不起作用。

想知道是否有任何方法可以做到这一点。

我已经看到这个使用画布进行像素化。想知道是否没有其他解决方案可以在不使用 JS/canvas 的情况下工作。

<style>
  div {
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center center;
  }
</style>
<div style='background-image: url(/100px.jpg)'></div>

4

1 回答 1

2

您可以使用 svg 过滤器进行像素化。然后,您可以为过滤器设置动画。要在 div 背景上使用过滤器,您只需进行过滤:url(#filterid)

放在一起看起来像这样:

#myDiv::before{
content:"";
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
filter:url(#pixelate);
background-size:cover;
background-image:url(https://images.unsplash.com/photo-1475724017904-b712052c192a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2850&q=80)

}

#myDiv {
  position:relative;
  width:350px;
  height:250px;
}

.inside {
  position: relative;
}
<div id="myDiv"> <div class="inside"><h1>Hello</h1></div> </div>
<svg>
  <filter id="pixelate" x="0" y="0">
    <feFlood x="4" y="4" height="1" width="1" />
    <feComposite id="composite1" width="10" height="10" />
    <feTile result="a" />
    <feComposite in="SourceGraphic" in2="a" operator="in" />
    <feMorphology id="morphology" operator="dilate" radius="5" />
  </filter>

  <animate xlink:href="#composite1" id="anim-width" 
    attributeName="width" from="40" to="10" dur=".8s"
    fill="freeze" />  
  <animate xlink:href="#composite1" id="anim-height" 
    attributeName="height" from="40" to="10" dur=".8s"
    fill="freeze" />
  <animate xlink:href="#morphology" id="anim-radius" 
    attributeName="radius" from="20" to="5" dur=".8s"
    fill="freeze"/>
</svg>

请注意,我必须创建一个内部 div 并在伪元素上应用背景,::before但“很快”这将变得不必要,当支持backdrop-filter改进时。

参考:

像素化 svg 效果:https ://codesandbox.io/s/km3opvn6yv

动画 svg 过滤器:https ://codepen.io/chriscoyier/pen/dPRVqL

背景过滤器:https ://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter

于 2019-06-04T21:51:10.750 回答