Javascript 如何将变量指定给context.fillStyle

Javascript 如何将变量指定给context.fillStyle,javascript,arrays,html,canvas,Javascript,Arrays,Html,Canvas,我试图使矩形随机出现在画布上,并试图使矩形的颜色从数组颜色中随机选择。当我将context.fillstyle的值设置为颜色时,它会起作用,但当我将context.fillstyle的值设置为RandomColor时,矩形会变为黑色。任何帮助都将不胜感激。提前谢谢 <!DOCTYPE HTML> <html> <head> <script> function init(){ var canvas = document.getElementById(

我试图使矩形随机出现在画布上,并试图使矩形的颜色从数组颜色中随机选择。当我将context.fillstyle的值设置为颜色时,它会起作用,但当我将context.fillstyle的值设置为RandomColor时,矩形会变为黑色。任何帮助都将不胜感激。提前谢谢

<!DOCTYPE HTML>
<html>
<head>
<script>
function init(){
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var x = Math.floor(Math.random()*100)+1;
var y = Math.floor(Math.random()*100)+1;
var width = Math.floor(Math.random()*300)+1;
var height = Math.floor(Math.random()*100)+1;
var colors = ["green", "blue", "red", "pink", "yellow"]
var randomColor = colors[Math.floor((Math.random)*colors.length)];
context.fillStyle = randomColor;
context.fillRect(x,y,width,height);
}
</script>
<form>
<input type="button" value="submit" onClick="init()">
< /form>
</body>
</html>

函数init(){
var canvas=document.getElementById(“canvas”);
var context=canvas.getContext(“2d”);
var x=数学地板(数学随机()*100)+1;
var y=Math.floor(Math.random()*100)+1;
var width=Math.floor(Math.random()*300)+1;
var height=Math.floor(Math.random()*100)+1;
变量颜色=[“绿色”、“蓝色”、“红色”、“粉色”、“黄色”]
var randomColor=颜色[数学地板((数学随机)*颜色.长度)];
context.fillStyle=randomColor;
fillRect(x,y,宽度,高度);
}


您需要将Math.random更改为Math.random()。您忘记了使用括号,因此没有调用随机函数

function init() {
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    var x = Math.floor(Math.random() * 100) + 1;
    var y = Math.floor(Math.random() * 100) + 1;
    var width = Math.floor(Math.random() * 300) + 1;
    var height = Math.floor(Math.random() * 100) + 1;
    var colors = ["green", "blue", "red", "pink", "yellow"]
    var randomColor = colors[Math.floor((Math.random()) * colors.length)];
    context.fillStyle = randomColor;
    context.fillRect(x, y, width, height);
}
见下文

通过将输出打印到控制台,您会发现它

console.log(Math.floor((Math.random()) * colors.length)) // -> NaN