js实现倒影
使用 CSS -webkit-box-reflect 实现倒影
CSS 原生提供 -webkit-box-reflect 属性可直接为元素创建倒影。需注意浏览器兼容性(主要支持 WebKit 内核浏览器如 Chrome/Safari):
.target-element {
-webkit-box-reflect: below 10px linear-gradient(transparent, rgba(0, 0, 0, 0.3));
}
below 10px表示倒影出现在元素下方 10px 处linear-gradient控制倒影渐变效果
通过 Canvas 动态生成倒影
适用于需要动态控制倒影效果的场景:
function createReflection(elementId) {
const canvas = document.createElement('canvas');
const img = document.getElementById(elementId);
canvas.width = img.width;
canvas.height = img.height * 0.6; // 倒影高度
const ctx = canvas.getContext('2d');
ctx.translate(0, img.height);
ctx.scale(1, -0.6); // 垂直翻转并压缩
ctx.drawImage(img, 0, 0, img.width, img.height);
ctx.globalCompositeOperation = 'destination-out';
const gradient = ctx.createLinearGradient(0, 0, 0, img.height);
gradient.addColorStop(0, 'rgba(0,0,0,0.7)');
gradient.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, img.width, img.height);
return canvas;
}
SVG 实现方案
利用 SVG 的滤镜效果创建更复杂的倒影:
<svg>
<filter id="reflect" x="0" y="0" width="1" height="1">
<feGaussianBlur in="SourceAlpha" stdDeviation="2"/>
<feOffset dy="5" result="offsetblur"/>
<feComponentTransfer>
<feFuncA type="linear" slope="0.5"/>
</feComponentTransfer>
<feMerge>
<feMergeNode/>
<feMergeNode in="SourceGraphic"/>
</feMerge>
</filter>
</svg>
纯 JavaScript 实现方案
通过 DOM 操作复制元素并应用变换:

function createDomReflection(element) {
const clone = element.cloneNode(true);
clone.style.transform = 'scaleY(-1)';
clone.style.opacity = '0.5';
clone.style.filter = 'blur(2px)';
element.parentNode.appendChild(clone);
return clone;
}
注意事项
- 性能考虑:CSS 方案性能最优,Canvas 适合动态内容
- 浏览器兼容:
-webkit-box-reflect需前缀,现代浏览器支持 Canvas/SVG - 交互处理:倒影元素可能需要额外事件处理
- 移动端适配:高分辨率设备需调整模糊度参数






