Alpha not working in fill()

Hello,

I’m taking a number of Processing sketches and converting them to p5.js. I have converted this sketch from Processing to p5 but I can’t quite figure out why the alpha isn’t working here. Any insights?

// Arrays are a way to create variables in bulk.
// A regular variable can store only one value.
// An array can store multiple values.

// because we now have 3 arrays which will be used in conjunction with each other (ie: same length, let's use a variable
// to determined their length this way we can easily experiement with a different number of circles by changing 'n' only 
var n = 100;

// this creates an array of 100 var variables called "hues"
var hues = new Array(n);

// let's also create two arrays that will store random x and y coordinates
var x = new Array(n);
var y = new Array(n);

function setup() {
	// set some initital conditions
	createCanvas(600, 600);
	colorMode(HSB);
	noStroke();

	// fill the arrays with random values
	// note that we use the length of the array (hues.length) to set our loop condition
	for (var i = 0; i < hues.length; i++) {
		// here, the counter "i" is used as an index to enter the hues into the array
		hues[i] = random(255);
		x[i] = random(width);
		y[i] = random(height);
	}
}

function draw() {
	background(255);

	// here, we use...
	for (var i = 0; i < hues.length; i++) {

		// ...to make each circle's diameter proportional to their distance to the mouse cursor
		var diameter = dist(x[i], y[i], mouseX, mouseY);

		// look up the hue for that circle by using "i" as an index into the array "hues" eg: hues[i]
		fill(hues[i], 255, 255, 60);
		// do the same for x and y:
		ellipse(x[i], y[i], diameter, diameter);
	}
}
2 Likes

According to colorMode()'s reference: p5js.org/reference/#/p5/colorMode

Default range for the alpha channel is from 0 to 1:

Setting colorMode(HSB) lets you use the HSB system instead.
By default, this is colorMode(HSB, 360, 100, 100, 1).

So, either use colorMode(HSB, 255, 255, 255, 255); or replace the alpha value 60 w/ .6:
fill(hues[i], 255, 255, 60); -> fill(hues[i], 100, 100, .6);

Also, for performance reasons, always invoke method fill() after using the Array constructor:

var hues = new Array(n); -> const hues = Array(n).fill();

1 Like

Thanks so much for your response GoToLoop. That definitely worked.

I’m wondering if you could expand on how using fill() as you suggested would work in my use case? My array is being filled with random numbers–how would I do that using your method?

Thanks again :slight_smile:

1 Like
  • I’ve mentioned that as an extra tip, not as a solution for anything!
  • Invoking method Array::fill() opens up an opportunity for the JS’ VM to convert a sparse Array into a dense/compact 1.
  • Read more about it on this link: 2ality.com/2018/12/creating-arrays.html