You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CSS为带透明区域的图片添加动态闪光效果?

解决方案:用CSS遮罩实现仅在图标不透明区域显示闪光效果

可以通过CSS的**遮罩(mask)**属性实现需求,核心是用目标图标作为闪光素材的遮罩,让闪光只在图标不透明区域内显示,同时保留混合模式的色彩叠加效果,完全无需预合成图片。

修改后的代码

CSS

.icon {
    position: relative;
    display: inline-block;
    background-color: #000080;
}
.icon .type {
    width: 24px;
    height: 24px;
    position: absolute;
    top: 0;
    left: 0;
    object-fit: none;
    object-position: 0 0; /* 对应精灵图中目标图标的位置 */
    z-index: 10;
}
.icon .glint {
    width: 24px;
    height: 24px;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 11;
    mix-blend-mode: overlay;
    /* 关键:用目标图标作为遮罩,限制闪光显示范围 */
    mask-image: url(icons.png);
    mask-size: auto;
    mask-position: 0 0; /* 必须和目标图标的object-position一致 */
    mask-repeat: no-repeat;
    /* 兼容webkit内核浏览器 */
    -webkit-mask-image: url(icons.png);
    -webkit-mask-size: auto;
    -webkit-mask-position: 0 0;
    -webkit-mask-repeat: no-repeat;
}

HTML

<div class="icon">
    <img class="type" src="icons.png">
    <img class="glint" src="glint.webp">
</div>

核心逻辑说明

  • 遮罩属性:通过mask-image将目标图标设为闪光素材的遮罩,闪光只会在遮罩的不透明区域显示,完美贴合图标不规则形状
  • 位置匹配:因为目标图标是CSS精灵图,必须保证mask-position和图标的object-position参数完全一致,否则遮罩会错位
  • 修正错误属性:原代码中的z-order是无效属性,替换为标准的z-index来控制图层顺序
  • 混合模式:保留mix-blend-mode: overlay实现类似《我的世界》附魔物品的色彩叠加效果,也可根据需求换成lighten等其他模式

该方案既控制了文件大小,又降低了后续维护成本,完全满足你的需求。

内容的提问来源于stack exchange,提问作者Carl Colijn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 16:23:10