We are about to switch to a new forum software. Until then we have removed the registration on this forum.
This is my first attempt at using p5.js I've been starting to build out some simple code for a college project but before I went too far, I wanted to figure out how to change the colors of each individual arc of my pie chart to a pre-determined color. Right now, they are simply ranges of gray.
I've searched through p5.js' website as well as the Processing forums but I cannot find a straight answer. And everything that I've tried has not worked.
Here is my code thus far:
var angles = [ 100, 75, 50, 90, 45];
function setup() {
createCanvas(1024, 768);
noStroke();
noLoop();
}
function draw() {
background(50,100,255,50);
pieChart(300, angles);
ellipseMode(CENTER);
fill(0,0,0,100);
noStroke();
ellipse(360, 360, 75, 75);
fill(255);
noStroke();
ellipse(360, 360, 72, 72);
}
function pieChart(diameter, data) {
var lastAngle = 0;
for (var i = 0; i < data.length; i++) {
var gray = map(i, 0, data.length, 0, 255);
fill(gray);
stroke(255);
strokeWeight(1.5);
arc(360, 360, diameter, diameter, lastAngle, lastAngle+radians(angles[i]));
line(360, 360, 360 + diameter/2 * cos(lastAngle), 360 + diameter/2 * sin(lastAngle));
lastAngle += radians(angles[i]);
}
}
Answers
Please, when posting code in this forum, highlight it and hit CTRL+K in order to format it! L-)
Unfortunately, P5.JS doesn't accept a whole value to represent an ARGB
color
like Java & JS Modes do so far! :(Unless it's gray scale, we've gotta pass the RGBA attributes 1-by-1 or as an array.
Therefore, if you wanna a
color
for each piece of that pie, best option is pass an array of RGB or RGBA arrays:hi @clandrie, if I understand correctly, you want the different slices to be different colors? in order to do that, you just need to pass in 3 values instead of 1 into line 27 where it says
fill(gray);
you might want to use HSB color mode also. so you could add
colorMode(HSB);
in setup and then replace line 27 with:fill(gray, 255, 255);
if you wanted to use predetermined colors you can use an array like @GoToLoop suggests above. you could first create an array of colors like this:
var colors = [ [255, 0, 0], [100, 200, 0], ... ];
then access them in line 27 like:
fill(colors[0]); first color in your array
orfill(colors[1]); // second color in your array
Hi @Imccart Thank you so much! Your code worked perfectly! :-bd
Here is my new code for anyone interested:
Hi! Converted "DrawPieChart" in Java too. Having same sketch in both languages may help folks trying P5.JS!
You can also see it running online via Processing.JS (JS Mode): =:)
http://studio.processingtogether.com/sp/pad/export/ro.9cEo3JxuOM3wG/latest
And why not "CoffeeScript Mode" version as well?: O:-)