случайный цвет фигуры.холст.Javascript - PullRequest
0 голосов
/ 15 мая 2018

У меня есть задача применить произвольный цвет к прямоугольнику каждый раз, когда он начинает двигаться сверху вниз. теперь он работает правильно, за исключением первой итерации, так как прямоугольник имеет черный (по умолчанию) цвет фона. Так как же применить случайный цвет к прямоугольнику с самого первого раза?

var currentPos = 0;

function animate() {  
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');  
  ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientWidth); 
  ctx.fillRect(100, currentPos, 20, 20);
  currentPos += 1;
  if(currentPos >= canvas.clientHeight) {
    currentPos = 0;
    ctx.fillStyle = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
  } 

  requestAnimationFrame(animate);   
}

document.body.onload = animate;
<doctype html>
<html>
  <head>
    <style>
      canvas {        
        background: yellow;
      }
    </style>
  </head>
  <body>
    <canvas width="200" height="180" id="canvas"></canvas>      
  </body>
</html>

1 Ответ

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

var currentPos = 0;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');  
ctx.fillStyle = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';

function animate() {  
  ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientWidth); 
  ctx.fillRect(100, currentPos, 20, 20);
  currentPos += 1;
  if(currentPos >= canvas.clientHeight) {
    currentPos = 0;
    ctx.fillStyle = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
  } 

  requestAnimationFrame(animate);   
}

document.body.onload = animate;
<doctype html>
<html>
  <head>
    <style>
      canvas {        
        background: yellow;
      }
    </style>
  </head>
  <body>
    <canvas width="200" height="180" id="canvas"></canvas>      
  </body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...