2011-09-16 61 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