2016-10-06 61 views
1

我試圖使一個矩形逐漸改變它的顏色(淡入淡出)使用JavaScript後按下按鈕從黃色變白。可悲的是我的代碼不起作用。你能幫我弄清楚代碼有什麼問題,以及如何解決它?逐漸褪色使用JS

我剛開始學習Javascript。對不起,如果這個問題很愚蠢。先謝謝你。

這是我的代碼:

<!DOCTYPE html> 
<html> 
<body> 

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"> 
Your browser does not support the HTML5 canvas tag.</canvas> // create canvas to work with 

<button onclick="fade(ctx)">Change the colour!</button> 

<script> 

var c = document.getElementById("myCanvas"); 
var ctx = c.getContext("2d"); //set context 
ctx.rect(20, 20, 150, 100); // draw a rectangle 
ctx.stroke(); // with border 
ctx.fillStyle="#FFFF00"; // fill with yellow 
ctx.fillRect(20,20,150,100); 

function fade(ctx) { // fade function responsible for changing colour 

var dom = getElementById(ctx), level = 1; // new object based on rectangle object, initial iterator is set to 1 

function step() { // inner step function 
    var h = level.toString(16); 
    dom.fillStyle = '#FFFF' + h + h; // construct a new colour using h variable 

    if (level < 15) { 
    level += 1; 
    setTimeout(step, 100); // do this after every 100 ms 
    } 

    } 

    setTimeout(step, 100); 
} 

</script> 

</body> 
</html> 
+1

爲什麼你不使用CSS? –

+0

我正在學習Javascript,並想了解如何使用內部函數和超時。我不知道如何使用CSS逐漸改變顏色。 –

+1

這裏只有CSS:http://codepen.io/impressivewebs/pen/zohgt –

回答

0

你幾乎與您的代碼有它雖然。你已經將上下文傳遞給函數了,所以不需要getElementById(ctx)位。事實上,這會給你一個錯誤,所以從你的代碼中刪除該行。而是直接設置填充樣式在這樣的CTX變量:

ctx.fillStyle = '#FFFF' + h + h; 

,你還需要重新繪製矩形,所以加入這一行:您設置的顏色後

ctx.fillRect(20,20,150,100); 

。這將做到這一點。

+0

謝謝你試圖幫助。我不太清楚如何擺脫getElementById(ctx),因爲我認爲我需要爲對象添加'level'屬性。基於你的迴應,我嘗試做出以下更改,但它仍然不適用於我。可能我不太明白你建議做什麼修改:[鏈接] http://pastebin.com/mBSq8Rum(http://pastebin.com/mBSq8Rum) –

+0

所以,只要刪除dom變量的聲明,你仍然需要級別變量。該行應該是:'var level = 1;'否則代碼看起來正確。 –

+0

太棒了!我做了改變,它的工作!非常感謝你! [http://pastebin.com/kyTAktTn](http://pastebin.com/kyTAktTn) –