2011-09-01 75 views
2

也许我没有使用的Math.random()正确,但我想不出我做错了什么:不可能直接在fillStyle中生成随机数字吗?

ctx.fillStyle = "rgb(Math.floor(Math.random()*256),Math.floor(Math.random()*256),Math.floor(Math.random()*256))"; 
ctx.fillRect(0,0,canvas.width,canvas.height); 

回答

3

填充样式是一个字符串。你需要使用字符串连接来做你想做的事情。像这样:

ctx.fillStyle = "rgb("+ 
    Math.floor(Math.random()*256)+","+ 
    Math.floor(Math.random()*256)+","+ 
    Math.floor(Math.random()*256)+")"; 
ctx.fillRect(0,0,canvas.width,canvas.height); 
+0

太棒了,谢谢! – njk

+0

有没有一种方法可以将rgb值(或rgba或您做bw或bwa)存储为var?如在:color myCol = rgb(0,255,96); 或者我只是将它存储为一个字符串,如var myCol =“rgb(0,255,96)”; – njk

+0

没关系,这个问题基本上是回答[这里](http://stackoverflow.com/questions/6088366/rgb-value-as-variable)(似乎答案是“是的,这是一个字符串”) – njk