2017-12-02 328 views
1

我想畫一個畫布矩形,每個負載都會改變顏色。這裏是我的代碼:HTML5畫布 - 爲什麼矩形的顏色總是返回黑色?

window.onload = function() { 
    var can = document.getElementById("lol"); 
    var ctx = can.getContext("2d"); 
    var colors = ["rgba(255,0,0,1)", "rgba(0,255,0,1)", "rgba(0,0,255,1)"]; 

    ctx.fillStyle = colors[Math.random() * 3]; 
    ctx.fillRect(40,40,30,25); 
} 

然而,每當我打開一個網頁,顏色應改爲紅色,藍色或綠色,但顏色是黑色的持續。

爲什麼會發生這種情況?我的代碼有什麼問題?

+1

您的日常隨機很少返回一個整數 –

回答

3

您沒有正確選取隨機數。你的隨機函數幾乎不會返回一個整數。

Read more about Math.random here.

這裏是你想要做什麼:

var can = document.getElementById("lol"); 
 
var ctx = can.getContext("2d"); 
 
var colors = ["rgba(255,0,0,1)", "rgba(0,255,0,1)", "rgba(0,0,255,1)"]; 
 

 
ctx.fillStyle = colors[Math.floor(Math.random() * 3)]; 
 
ctx.fillRect(40,40,30,25);
<canvas id="lol"></canvas>

2

你需要一個整數值,用於訪問數組元素。

ctx.fillStyle = colors[Math.floor(Math.random() * 3)]; 

我建議使用數組作爲隨機數因子的長度(一個恆定vaue可能出錯,如果單元的計數改變後)。

ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];