我认为您在寻找玻璃(或者说是钻石)时期望的是其不完全透明或平坦,它会反射周围环境并且轻微地畸变背景。你可以通过径向渐变来呈现反射的效果。然而畸变就比较棘手了。您可以移动和缩放对象后面的每个像素,但这将难以实现,更不用说非常慢了。另一种方法是实现一个非常细腻、快速变化的渐变,它将呈现下方像素的畸变效果,即使实际上并没有发生任何变化。
下面是一个带有反射和畸变效果的玻璃窗的实现。
<html>
<canvas id="canvas" style="position:fixed;">
</canvas>
<script type="text/javascript">
document.getElementById("canvas").height=window.innerHeight;
document.getElementById("canvas").width=window.innerWidth;
ctx=document.getElementById("canvas").getContext("2d");
textWidth=ctx.measureText("Hello World! ");
textWidth=Math.ceil(textWidth.width);
ctx.lineWidth=3;
targetWidth=Math.floor(window.innerWidth/textWidth)*textWidth;
for(i=0;i<500;i++)
{
ctx.fillText("Hello World! ",((i*textWidth)%(targetWidth)),(16*Math.floor((i+1)*textWidth/window.innerWidth)+16));
}
var glass = ctx.createRadialGradient(80,110,0,100,140,100);
for(i=0;i<=100;i++)
{
redComponent=Math.round(210-(i%11));
greenComponent=Math.round(245-(i%7));
blueComponent=Math.round(255-(i%5));
opacity=Math.round(((i%3)+1)*Math.sin(i/200*Math.PI)*1000)/3000;
glass.addColorStop(i/100,"rgba("+redComponent+","+greenComponent+","+blueComponent+","+opacity+")");
}
glass.addColorStop(1,"rgba(0,0,0,0)")
ctx.fillStyle=glass;
ctx.beginPath();
ctx.translate(100,0);
ctx.moveTo(100,100);
ctx.lineTo(187,150);
ctx.lineTo(137,237);
ctx.lineTo(50,187);
ctx.lineTo(100,100);
ctx.closePath;
ctx.fill();
ctx.stroke();
</script>
</html>
结果是: