vendredi 1 mai 2020

Is there a way to use a variable as a parameter in rgba() in JavaScript?

This is my Javascript code.

var radius = random(20,200);
    var randRed = random(210,255);
    var randAlpha = random(0.25,0.4);
    var Color = 'rgba(255,255,255,0.25)';
    this.x = random(100, 700);
    this.y = random(100, 500);
    this.width = radius;
    this.height = radius;
    this.color = Color;
    this.velocityX = random(-5, +5);
    this.velocityY= random(-5, +5);

For context, this is used in a constructor in a class Bubble to create randomized circular bubbles. I found a way to randomize radius and position, but is there any way to use randRed and randAlpha as the red and alpha values for the rgba() in the Color variable?

I want to be able to do something like:

var Color = 'rgba(randRed,255,255,randAlpha);

Is this possible? Here is the rest of the code:

class Bubble {

  constructor() {
    var allInstances = [];

    var radius = random(20, 200);
    var randRed = random(210, 255);
    var randAlpha = random(0.25, 0.4);
    var Color = 'rgba(255,255,255,0.25)';
    this.x = random(100, 700);
    this.y = random(100, 500);
    this.width = radius;
    this.height = radius;
    this.color = Color;
    this.velocityX = random(-5, +5);
    this.velocityY = random(-5, +5);

    this.display = function() {
      stroke(255);
      fill(this.color);
      ellipse(this.x, this.y, this.width, this.height);
    }

    this.move = function() {
      this.x = this.x + this.velocityX;
      this.y = this.y + this.velocityY;
    }

  }
}

var bubbles = [];

function setup() {
  createCanvas(800, 600);
  bubble1 = new Bubble();
  bubble2 = new Bubble();
  bubble3 = new Bubble();
  bubble4 = new Bubble();
  bubble5 = new Bubble();
  bubble6 = new Bubble();
}


function draw() {
  background(56, 226, 232);
  bubble1.move();
  bubble2.move();
  bubble3.move();
  bubble4.move();
  bubble5.move();
  bubble6.move();

  bubble1.display();
  bubble2.display();
  bubble3.display();
  bubble4.display();
  bubble5.display();
  bubble6.display();
}

setInterval(function() {
  setup();
  draw();
}, 2900);
html,
body {
  margin: 0;
  padding: 0;
}

canvas {
  display: block;
}
<!DOCTYPE html>
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.dom.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.sound.min.js"></script>
  <link rel="stylesheet" type="text/css" href="style.css">
  <meta charset="utf-8" />
</head>

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

</html>



Aucun commentaire:

Enregistrer un commentaire