changing background color randomly in canvas

时间:2018-09-18 19:59:50

标签: javascript html5-canvas

so i want the color black in the background to change randomly after every 3 secs , so i have an idea i can use a a random fucntion linked with color combination, but i just don't know how to make a logic out of that or the correct syntax to apply .if you have any other alternatives that would be great .Really hoping to get a correct working solution to this.this is my javascript

<!DOCTYPE html5>
<html>
<head>
  <title>3D Stars in HTML5 Canvas</title>
 
  <script type='text/javascript'>
    MAX_DEPTH = 32;
 
    var canvas, ctx;
    var stars = new Array(512);
 
    window.onload = function() {
      canvas = document.getElementById("tutorial");
      if( canvas && canvas.getContext ) {
        ctx = canvas.getContext("2d");
        initStars();
        setInterval(loop,15);
       }
    }
 
    /* Returns a random number in the range [minVal,maxVal] */
    function randomRange(minVal,maxVal) {
      return Math.floor(Math.random() * (maxVal - minVal - 1)) + minVal;
    }
 
    function initStars() {
      for( var i = 0; i < stars.length; i++ ) {
        stars[i] = {
          x: randomRange(-25,25),
          y: randomRange(-25,25),
          z: randomRange(1,MAX_DEPTH)
         }
      }
    }
 
    function loop() {
      var halfWidth  = canvas.width / 2;
      var halfHeight = canvas.height / 2;
 
      ctx.fillStyle = "rgb(0,0,0)";
      ctx.fillRect(0,0,canvas.width,canvas.height);
 
      for( var i = 0; i < stars.length; i++ ) {
        stars[i].z -= 0.2;
 
        if( stars[i].z <= 0 ) {
          stars[i].x = randomRange(-25,25);
          stars[i].y = randomRange(-25,25);
          stars[i].z = MAX_DEPTH;
        }
 
        var k  = 128.0 / stars[i].z;
        var px = stars[i].x * k + halfWidth;
        var py = stars[i].y * k + halfHeight;
 
        if( px >= 0 && px <= 500 && py >= 0 && py <= 400 ) {
          var size = (1 - stars[i].z / 32.0) * 5;
          var shade = parseInt((1 - stars[i].z / 32.0) * 255);
          ctx.fillStyle = "rgb(" + shade + "," + shade + "," + shade + ")";
          ctx.fillRect(px,py,size,size);
        }
      }
    }
  </script>
    </head>
<body>
  <canvas id='tutorial' width='500' height='400'>
    Your browser does not support HTML5 canvas.
    Please upgrade your browser.
  </canvas>
</body>
</html>

0 个答案:

没有答案