Придайте каждой фигуре на холсте HTML5 случайный цвет - PullRequest
0 голосов
/ 25 мая 2018

Попытка создать страницу квадратов, каждый из которых имеет свой цвет.Пока у меня есть генератор случайных цветов, который работает, но до сих пор он устанавливает каждый квадрат на один и тот же случайный цвет при каждой загрузке страницы, просто пытаясь найти способ придать каждому квадрату другой случайный цвет.

Я пытался использовать функции для создания другого цвета, но это не очень хорошо работает, вот код для моего генератора случайных чисел:

var red = Math.floor(Math.random()* 255);
var green = Math.floor(Math.random() * 255);
var blue = Math.floor(Math.random() * 255);

А вот код для одного из моих квадратов(все они имеют одинаковый код, просто разные координаты)

ctx.rect(820, 50,100,100);
ctx.closePath();
ctx.fillStyle = "rgb("+red+","+green+"," +blue+" )";    
ctx.fill();

Весь код здесь:

<html>
<canvas id="canvas1" height="768" width="1024" style="border: 1px solid #000000;"></canvas>

<script>
  var canvas = document.getElementById("canvas1");
  var ctx = canvas.getContext("2d");

  var red = Math.floor(Math.random() * 255);
  var green = Math.floor(Math.random() * 255);
  var blue = Math.floor(Math.random() * 255);

  ctx.beginPath();
  ctx.rect(70, 50, 100, 100);
  ctx.closePath();
  ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
  ctx.fill();

  ctx.rect(220, 50, 100, 100);
  ctx.closePath();
  ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
  ctx.fill();

  ctx.rect(370, 50, 100, 100);
  ctx.closePath();
  ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
  ctx.fill();

  ctx.rect(520, 50, 100, 100);
  ctx.closePath();
  ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
  ctx.fill();

  ctx.rect(670, 50, 100, 100);
  ctx.closePath();
  ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
  ctx.fill();

  ctx.rect(820, 50, 100, 100);
  ctx.closePath();
  ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
  ctx.fill();
</script>


</html>

Ответы [ 3 ]

0 голосов
/ 25 мая 2018

Это то, что вам нужно сделать:

 var canvas = document.getElementById("canvas1");
    var ctx = canvas.getContext("2d");
    function RandColor() {
      var letters = '0123456789ABCDEF';
      var color = '#';
      for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    }
        

        ctx.beginPath();
        ctx.fillStyle = RandColor();
        ctx.fillRect(70,50,100,100);
        ctx.fillStyle = RandColor();
        ctx.fillRect(220, 50,100,100);
<canvas id="canvas1" />

Вы должны создать функцию для случайного цвета (вместо создания одного случайного цвета) и назвать ее так:

    ctx.fillStyle = RandColor();
    ctx.fillRect(70,50,100,100);

длякаждый прямоугольник, который вы хотите создать

0 голосов
/ 25 мая 2018

Вы должны захотеть создать функции для простого добавления объектов, например:

// Add function to pick random rgb values
function getRandomRGB() {
  var r = Math.floor(Math.random() * 255);
  var g = Math.floor(Math.random() * 255);
  var b = Math.floor(Math.random() * 255);
  return "rgb(" + r + "," + g + "," + b + ")";
}

// You may want to add this other function to simplify your code, too
function addFilledRect(arg1, arg2, arg3, arg4) {
  // Inside this function, we're using the ctx variable from outside
  ctx.fillStyle = getRandomRGB();       // Call the function to get a random rgv color
  ctx.fillRect(arg1, arg2, arg3, arg4); // Create the filled rectangle
}

var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");

// Then, you can call the above function multiple times
addFilledRect(70, 50, 100, 100);
addFilledRect(220, 50, 100, 100);
addFilledRect(370, 50, 100, 100);
addFilledRect(520, 50, 100, 100);
addFilledRect(670, 50, 100, 100);
addFilledRect(820, 50, 100, 100);
<html>
  <canvas id="canvas1" height="768" width="1024" style="border: 1px solid #000000;"></canvas>
</html>

Надеюсь, это поможет.

0 голосов
/ 25 мая 2018

Это устанавливает цвета только один раз, прежде чем вы начнете рисовать свои прямоугольники;

var red = Math.floor(Math.random()* 255);
var green = Math.floor(Math.random() * 255);
var blue = Math.floor(Math.random() * 255);

Вы можете создать функцию, которая делает это и возвращает значения;

function getRandomColour(){
  var red = Math.floor(Math.random()* 255);
  var green = Math.floor(Math.random() * 255);
  var blue = Math.floor(Math.random() * 255);

  return "rgb("+red+","+green+"," +blue+" )";  
}

В качестве альтернативы, вы могли быпредварительно определите значения прямоугольников в массиве и обведите их, чтобы нарисовать прямоугольники.Будет меньше кода.

var canvas = document.getElementById("canvas1");
    var ctx = canvas.getContext("2d");


function getRandomColour(){
  var red = Math.floor(Math.random()* 255);
  var green = Math.floor(Math.random() * 255);
  var blue = Math.floor(Math.random() * 255);

  return "rgb("+red+","+green+"," +blue+" )";  
}

ctx.fillStyle = getRandomColour();
ctx.fillRect(70,50,100,100);

ctx.fillStyle = getRandomColour();
ctx.fillRect(10,10,100,100);
<canvas id="canvas1"></canvas>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...