Skip to content

Instantly share code, notes, and snippets.

@tomstuder
Created June 3, 2016 11:36
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tomstuder/45fc62023a660a2a2b1dede2c8727977 to your computer and use it in GitHub Desktop.
How can i convert rgb to hex in p5?
// 15538: Uncaught TypeError: Cannot read property 'toString' of undefined
function setup() {
createCanvas(400,400);
background(100);
}
function draw() {
// var s = second();
// var shex= color(map(s,0,59,0,100));
// var shex2= hex(s,6);
// var test_color = color(255, 204, 0);
// var hexi = String(s);
var c = color('rgb(255, 204, 0)');
fill(c);
rect(10,10,380,300);
textSize(20);
fill(255);
// text(s,width/2-40,height/2);
// text(shex,width/2-40,height/2 + 30);
// text("#"+ shex2,width/2-40,height/2 + 60);
// text(hexi,width/2-40,70);
// text(typeof hexi,width/2-40,90);
text(c,width/2-40,height/2);
text(hex(c,6),width/2-40,height/2+30);
}
@fezde
Copy link

fezde commented Jun 3, 2016

Quite brute force... but works

int r = 255;
int g = 204;
int b = 0;
int c = color(r,g,b);
String hx = "#" + hex(r,2) + hex(g,2) + hex(b,2);
println(c);
println(hx);

this outputs

-13312

FFCC00

It is processing not p5js - but should work very similar

@tomstuder
Copy link
Author

IT WORKS!!!

function setup() {
  createCanvas(300, 300);
  background(255,0,0);

  var r = hour();
  var g = minute();
  var b = second();
  var c = color(r,g,b);
  var hx = "#" + hex(r,2) + hex(g,2) + hex(b,2);
  fill(0);
  text(c,100,100);
  text(hx,100,125);
}

function draw() {
}

@tomstuder
Copy link
Author

function setup() {
  createCanvas(300, 300);
}

function draw() {
  var r = hour();
  var g = minute();
  var b = second();

  var r2 = map(r,0,23,0,255);
  var g2 = map(g,0,59,0,255);
  var b2 = map(b,0,59,0,255);
  var c2 = color(r2,g2,b2);

  var hx = "#" + hex(r2,2) + hex(g2,2) + hex(b2,2);

  background(c2);
  fill(255);
  textSize(20);
  text(c2,30,120);
  text(hx,30,145);
}

@PenguinOfThunder
Copy link

Or, if you just want to be silly:
var hx='#'+('000000'+(r<<16|g<<8|b).toString(16)).slice(-6); // r, g, and b are ints 0..255

@everythingability
Copy link

The p5 code above doesn't work... or rather, it did... then it didn't on some colours.

Use thise.

myColor.toString('#rrggbb')

@furf
Copy link

furf commented Feb 8, 2023

you can rewrite:

  var hx = "#" + hex(r2,2) + hex(g2,2) + hex(b2,2);

as:

  const hx = `#${hex([r2, g2, b2], 2).join('')}`;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment