【问题标题】:Draw circle with random color on canvas在画布上用随机颜色绘制圆圈
【发布时间】:2015-08-30 15:48:50
【问题描述】:

您好,我尝试使用函数在画布上绘制一个随机颜色的球,但它不起作用。我该如何解决语法位于ctx.fillStyle = 'JSON.stringify(getRandomElement(circles))'; 的问题?

未捕获的引用错误:黄色未定义

    function drawcircles() {
function getRandomElement(array) {
  if (array.length == 0) {
    return undefined;
  }
  return array[Math.floor(Math.random() * array.length)];
}

var circles = [
  yellow,
  red,  
  blue
];

ctx.beginPath();
      ctx.arc(ballx * 108, canvasHeight / 2, x*5, 0, 2*Math.PI, false);
      ctx.fillStyle = 'JSON.stringify(getRandomElement(circles))';
      ctx.fill();
ctx.closePath;

}

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    在您的代码中,数组circles 中的yellowredblue 是变量,它们尚未定义。因此,您可以 a) 将 HEX 代码放入这些变量中,或者 b) 将其替换为 HEX 代码。

    a) 例如

    var yellow = "#ffff00";  //first put the code for yellow in the variable
    var circles = [yellow]   //then put that variable in the list
    

    b) 例如

    var circles = ["#ffff00"];  //put the HEX code directly in the array
    

    【讨论】:

      【解决方案2】:

      为了利益。您可以使用此脚本生成随机的十六进制颜色:

      var color = '#' + Math.floor(Math.random() * 16777215).toString(16);

      更多关于为什么这有效的信息here

      【讨论】:

        【解决方案3】:

        如您所见here(对此的众多参考之一),填充样式颜色必须声明为 HEX。

        你必须在那个符号中改变你的颜色才能运行你的代码

        • 黄色是#FFFF00;
        • 红色是#FF0000;
        • 蓝色是#0000FF;

        你的数组会变成:

        var circles = [
          '#FFFF00',
          '#FF0000',  
          '#0000FF'
        ];
        

        无论如何,您的数组也是错误的,因为您没有将字符串值用单引号或双引号括起来,因为这些是字符串而不是 js 变量

        【讨论】:

        • 感谢您的帮助。错误消息消失但圆圈不会被绘制:/
        • 哦,我没有定义函数。我只复制到游戏循环中的普通绘图函数中。
        • 尝试将ctx.fillStyle = 'JSON.stringify(getRandomElement(circles))'; 更改为ctx.fillStyle = JSON.stringify(getRandomElement(circles));,不带引号
        • 没人,就是好奇
        • 这不是真的,ctx.fillStyle() 确实接受颜色为 rgba()rgb()hsl() 值。
        【解决方案4】:

        我的错。

        混乱的标签让我很困惑。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-04-09
          • 1970-01-01
          • 2013-10-24
          • 1970-01-01
          • 2012-11-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多