【问题标题】:How do I assign a variable to context.fillStyle如何将变量分配给 context.fillStyle
【发布时间】:2014-01-15 14:11:32
【问题描述】:

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

【问题讨论】:

    标签: javascript arrays html canvas


    【解决方案1】:

    您需要将 Math.random 更改为 Math.random()。您忘记了括号,因此没有调用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 2014-05-11
      • 2012-11-14
      • 2021-03-10
      • 2010-09-21
      • 2021-09-17
      • 2016-04-13
      相关资源
      最近更新 更多