<canvas> 钻石/玻璃效果

zeb*_*asz 4 javascript canvas html5-canvas

我正在制作画布动画,其中一个图像应该是钻石。

现在,我得到了这样的信息:

ctx[0].beginPath();
ctx[0].moveTo(0,-80);
ctx[0].lineTo(-60,-130);
ctx[0].lineTo(-36,-160);
ctx[0].lineTo(36,-160);
ctx[0].lineTo(60,-130);
ctx[0].closePath();
ctx[0].fillStyle = "rgba(175,175,255,0.7)";
ctx[0].fill();
Run Code Online (Sandbox Code Playgroud)

它绘制了一个简单的浅蓝色半透明钻石形状。

这太简单了,但我在“颜色”方面遇到了严重的问题。我猜类似玻璃的东西应该可以解决这个问题,但到目前为止我还没有发现任何有用的东西。如果有帮助的话,我可以根据需要添加尽可能多的线条,但颜色是我的主要问题。

这将是预渲染的,所以长而复杂的代码不是什么大问题。不过,我宁愿不使用图像。

总结一下:我需要画布的玻璃效果。有任何想法吗?

min*_*tea 5

我认为您在玻璃(或者大概是钻石)中寻找的是它不是完全透明或平坦的。相反,它反映了周围的环境,并稍微扭曲了背景。您可以通过径向渐变来呈现反射的外观。然而,这种扭曲更加棘手。您可以移动和缩放对象后面的每个像素,但这将非常难以实现,更不用说速度非常慢了。或者,您可以实现一个非常精细、快速变化的渐变,这会导致下面的像素出现扭曲,即使实际上没有发生任何扭曲。

这是具有反射和扭曲的玻璃板的实现。

<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>
Run Code Online (Sandbox Code Playgroud)

结果是: 结果图像