ILikeThePoopSmith
ILikeThePoopSmith

Reputation: 121

How does an rgb string, e.g., "rgb(255, 0, 0)" get converted into an actual color

I was following along an MDN article when I came across the following (more or less, with some minor modifications)

function random(min, max) {
  const num = Math.floor(Math.random() * (max - min + 1)) + min;
  return num;
}

function Ball(x, y, velX, velY, color, size) {
  this.x = x;
  this.y = y;
  this.velX = velX;
  this.velY = velY;
  this.color = color;
  this.size = size;
}

Ball.prototype.draw = function() {
  ctx.beginPath();
  ctx.fillStyle = this.color;
  ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
  ctx.fill();
}

Ball.prototype.update = function() {
  if (this.x + this.size >= width || this.x - this.size <= 0) {
    this.velX = -this.velX;
  }

  if (this.y + this.size >= height || this.y - this.size <= 0) {
    this.velY = -this.velY;
  }

  this.x += this.velX;
  this.y += this.velY;
}

while (balls.length < 25) {
  let size = random(10,20);
  let ball = new Ball(
    // ball position always drawn at least one ball width
    // away from the edge of the canvas, to avoid drawing errors
    random(0 + size,width - size),
    random(0 + size,height - size),
    random(-7,7),
    random(-7,7),
    "rgb(" + random(0,255) + ',' + random(0,255) + ',' + random(0,255) + ")",
    size
  );

  balls.push(ball);
}

Near the very bottom, there's an rgb string that uses random numbers to determine what color to make the balls. But it's just a string like "rgb(144, 96, 205)"; How does JavaScript know to convert that string into an actual rgb value? There doesn't seem to be anything in the code that is doing that.

Upvotes: 1

Views: 384

Answers (2)

Makwana Prahlad
Makwana Prahlad

Reputation: 967

Please try this code, To How does an rgb string, e.g., “rgb(255, 0, 0)” get converted into an actual color

function RGBToHex(rgb) {
  // Choose correct separator
  let sep = rgb.indexOf(",") > -1 ? "," : " ";
  // Turn "rgb(r,g,b)" into [r,g,b]
  rgb = rgb.substr(4).split(")")[0].split(sep);

  let r = (+rgb[0]).toString(16),
      g = (+rgb[1]).toString(16),
      b = (+rgb[2]).toString(16);

  if (r.length == 1)
    r = "0" + r;
  if (g.length == 1)
    g = "0" + g;
  if (b.length == 1)
    b = "0" + b;

  return "#" + r + g + b;
}

I hope this code will be useful to you.

Thank you.

Upvotes: 0

Kaiido
Kaiido

Reputation: 137171

This "rgb("[...] string is passed as the color parameter of the Ball constructor, which itself is set as the .color property of the Ball instance, which in turn is used to set the ctx.fillStyle in the draw method of the Ball instance.

It's when setting this ctx.fillStyle that the string is parsed as a CSS color.

Upvotes: 1

Related Questions