如果可以在没有画布的情况下对图像像素化进行动画处理,则仅使用 CSS



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

  • background-image设置为非常小的图像(例如 50px 或 100px)。
  • 在元素上设置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>

您可以使用 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

最新更新