Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

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

This comment has been minimized.

Copy link
Owner Author

tomstuder commented Jun 3, 2016

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

This comment has been minimized.

Copy link
Owner Author

tomstuder commented Jun 3, 2016

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

This comment has been minimized.

Copy link

PenguinOfThunder commented Jun 4, 2016

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.