在画布上制作形状的随机颜色

时间:2015-12-15 15:38:37

标签: javascript html5 canvas

我有一个在画布上制作随机形状的代码。 我想用随机颜色填充形状,为此我做了这个:

var R=(Math.floor(Math.random() * 255);
    var G=(Math.floor(Math.random() * 255);
    var B=(Math.floor(Math.random() * 255);
    var randColor='rgb(' + R +', ' + G + ',' + B +')';

    context.fillStyle=randColor;

我把它放在产生我的形状的功能中,但没有运气。 例如,我只把它放在makeRect函数中,但它也应该在makeCircle函数中。 谁能告诉我这里弄错了什么?

这是我的HTML:     

<head>
<link href="design.css" rel="stylesheet" />
</head>

<body>
     <h4> Enter below, and then press the canvas to save your work</h4>
  <canvas id="canvas" width="1000" height="750"></canvas>
  <br/>
  <br/>
  <span>
    How many Circles do you want?
    <input id="inCircle" />
    </span>
  <br/>How many Squers do you want?
  <input id="inSquer" />
  <br/>
  <button id="creat">Creat My Work</button>

  <script src="js.js"></script>
</body>

</html>

这是我的JavaScript:

var drawing = document.getElementById("canvas");
var context = drawing.getContext("2d");
var inSquer = document.getElementById("inSquer");
var inCircle = document.getElementById("inCircle");
var button = document.getElementById("creat");


button.addEventListener("click", function() {


  paint(parseInt(inSquer.value), parseInt(inCircle.value));
});

drawing.addEventListener("click", function() {
  saveImage();
});


function saveImage() {
  window.location = drawing.toDataURL("image/jpeg");
}

function paint(numOfRect, numOfCirc) {

  for (var makeIt = 0; makeIt < numOfRect; makeIt++) {
    makeRect(drawing, context);
    makeCircle(drawing, context);
  }
}

function makeCircle(drawing, context) {

  var radius = Math.floor(Math.random() * 100);
  var x = Math.floor(Math.random() * canvas.width);
  var y = Math.floor(Math.random() * canvas.height);

  context.beginPath();
  context.arc(x, y, radius, 0, 2 * Math.PI);
  context.fillStyle = "blue";
  context.fill();
}

function makeRect(drawing, context) {

  var w = Math.floor(Math.random() * 100);
  var x = Math.floor(Math.random() * canvas.width);
  var y = Math.floor(Math.random() * canvas.height);

    var R=(Math.floor(Math.random() * 255);
    var G=(Math.floor(Math.random() * 255);
    var B=(Math.floor(Math.random() * 255);
    var randColor='rgb(' + R +', ' + G + ',' + B +')';

    context.fillStyle=randColor;

    /*context.fillStyle="green";*/
    context.fillRect(x, y, w, w);
}

这是我的css:

h4{
text-align: center;
}
#canvas{
    margin-left: 250px;
    border: 1px solid black;

}

2 个答案:

答案 0 :(得分:0)

你的第一部分JS缺少一些括号。

var R = (Math.floor(Math.random() * 255)),
    G = (Math.floor(Math.random() * 255)),
    B = (Math.floor(Math.random() * 255)),
    randColor = 'rgb(' + R + ', ' + G + ',' + B + ')';

答案 1 :(得分:0)

你缺少一些括号

var R=(Math.floor(Math.random() * 255);
var G=(Math.floor(Math.random() * 255);
var B=(Math.floor(Math.random() * 255);

把它用于工作

var R=(Math.floor(Math.random() * 255));
var G=(Math.floor(Math.random() * 255));
var B=(Math.floor(Math.random() * 255));
相关问题