2011-09-16 60 views
4

我正在制作一个画布动画,其中一个图像应该是一颗钻石。<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(); 

绘制一个平淡,淡蓝色半透明的菱形。

这太简单了,但是我对“颜色”有严重的问题。我猜想像玻璃一样应该做的伎俩,但我到目前为止还没有发现任何有用的东西。如果需要,我可以根据需要添加尽可能多的线条,但颜色是我的主要问题。

这将被预先渲染,很长时间,复杂的代码是没有太大的问题。不过,我宁愿不使用图像。总结一下:我需要一个用于画布的glass-ish效果。有任何想法吗?

+0

我不知道答案,但如果你在谷歌图片查找“钻石载体”,你会看到他们主要是充满了黑色/在笔画中的白色渐变。这很容易在画布上完成,所以也许会有所帮助。 http://www.google.com/search?tbm=isch&q=diamond+vector – pimvdb

+0

http://thinkvitamin.com/code/how-to-draw-with-html-5-canvas/本网站有一个不错的教程关于如何使用渐变。 – Ivan

+0

@伊万谢谢。我知道如何使用渐变,但我仍然需要关于颜色选择的帮助。 – zebasz

回答

4

我认为你在玻璃(或者可能是钻石)中寻找的是它不完全透明或平坦。相反,它反映了周围的环境,并且略微扭曲了背景。您可以通过径向渐变来呈现反射的外观。但是,失真更棘手。你可以移动和缩放物体后面的每个像素,但这实现起来难以想象,更不用说慢慢的了。另外,你可以实现一个非常好的,快速移动的渐变,即使没有实际发生,也会给出下面像素的变形。

这里是一个反射和扭曲的玻璃窗格的实现。

<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> 

,其结果是: Image of Result