我試圖使一個矩形逐漸改變它的顏色(淡入淡出)使用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>
爲什麼你不使用CSS? –
我正在學習Javascript,並想了解如何使用內部函數和超時。我不知道如何使用CSS逐漸改變顏色。 –
這裏只有CSS:http://codepen.io/impressivewebs/pen/zohgt –