Reputation: 1964
I want to implement a p5.js example of the Nature of Code book.
The aim is to fill a canvas with pixels which brightness is randomly chosen by the Perlin Noise function. I was inspired by the Processing's Java equivalent one but what I obtain is not why I expected, it is an almost black canvas.
This is my code :
var increment = 0.02
function setup() {
createCanvas(100, 100)
noLoop()
}
function draw() {
background(0)
loadPixels();
var xoff = 0
for (var x = 0; x < width; x++) {
xoff += increment
var yoff = 0
for (var y = 0; y < height; y++) {
yoff += increment
var bright = floor(noise(xoff, yoff) * 255)
console.log('bright', bright, '(', x, ', ', y, ')')
pixels[x+y*width] = color(bright);
}
}
updatePixels();
}
My console.log displays a bright value which seems coherent. Do you see any problem in my code?
Upvotes: 0
Views: 913
Reputation: 645
The pixels array is flat with each 4 elements creating a pixel.
The first pixel is actually:
pixels[0] // red value of pixel, between 0-255
pixels[1] // green value of pixel, between 0-255
pixels[2] // blue value of pixel, between 0-255
pixels[3] // alpha value of pixel, between 0-255
However, when looking through the p5.js documentation I noticed there is a helper method set
which abstracts the setting of a pixel's color. To use the set
method all we need is a pixel's coordinates as well as a color
instance. Changing the color mode also allows us to easily create a color object with a given brightness.
Note: I've included a CDN link to p5.js so you can run the example.
const increment = 0.02;
function setup() {
createCanvas(200, 200);
noLoop();
}
function draw() {
background(0);
colorMode(HSB, 255);
let xOff = 0;
for (let x = 0; x < width; x++) {
let yOff = 0;
xOff += increment;
for (let y = 0; y < height; y++) {
yOff += increment
const n = noise(xOff, yOff); // noise
const h = 255; // hue
const s = 126; // saturation
const b = map(n, 0, 1, 0, 255); // brightness
const c = color(h, s, b); // color instance
set(x, y, c); // set pixel
}
}
updatePixels();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.8/p5.min.js"></script>
Upvotes: 1