在画布上绘制随机颜色的圆圈

时间:2015-08-30 15:48:51

标签: javascript html html5 canvas

您好我尝试在画布上用随机颜色绘制一个带有功能的球,但它不会起作用。如何修复语法位于ctx.fillStyle = 'JSON.stringify(getRandomElement(circles))';的权利?

  

未捕获的ReferenceError:未定义黄色

    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;

}

4 个答案:

答案 0 :(得分:1)

在您的代码中,数组yellow中的redbluecircles是变量,并且尚未定义它们。所以你可以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

答案 1 :(得分:1)

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

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

有关其原因的更多信息here

答案 2 :(得分:-1)

我的坏。

搞糊涂了我。

答案 3 :(得分:-1)

正如您所看到的here(许多参考文献中的一个),填充样式颜色必须声明为HEX。

您必须使用该符号转换颜色才能运行代码

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

您的阵列将变为:

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

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

相关问题