如何为context.fillStyle分配变量

时间:2013-12-28 01:11:28

标签: javascript html arrays html5 canvas

我试图让矩形在画布上随机出现,并且我试图从数组颜色中随机选择矩形的颜色。当我将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>

1 个答案:

答案 0 :(得分:0)

您需要将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);
}

请参阅以下fiddle

通过将输出打印到控制台,您可以找到它......

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