PGraphics issue
in
Programming Questions
•
1 year ago
As part of a larger ocean animation I've attempted drawing a linear gradient background offscreen in setup with PGraphics. Unfortunately, the background does not seem to stay static as the sketch runs, but quickly bleeds down in a matter of seconds.
- PGraphics sky;
- int numOfWaves = 3;
- Waves[] waves;
- void setup() {
- size(600,400);
- smooth();
- int startX = -50;
- int startY = height-150;
- int waveWidth = width+100;
- int waveHeight = 200;
- waves = new Waves[numOfWaves];
- for (int i = 0; i<numOfWaves; i++) {
- waves[i] = new Waves(startX,startY+(30*i),waveWidth,waveHeight);
- }
- makeBackground();
- }
- void draw() {
- image(sky,0,0);
- for (int i = 0; i<numOfWaves; i++) {
- waves[i].update();
- waves[i].display();
- }
- }
- void makeBackground() {
- sky = createGraphics(width,height,P2D);
- sky.beginDraw();
- sky.smooth();
- float skyA = 255;
- color skyC;
- sky.loadPixels();
- for (int y=0;y<height;y++) {
- for (int x=0;x<width;x++) {
- skyA = map(y,0,height,110,0);
- skyC = color(0,185,255,skyA);
- sky.set(x,y,skyC);
- }
- }
- sky.updatePixels();
- sky.endDraw();
- }
- class Waves {
- int layerWidth,layerHeight;
- float x,y;
- float xBound, yBound;
- float xMove, yMove;
- float xTheta,yTheta;
- PGraphics wave;
- PGraphics wMask; // wave Mask
- PGraphics wShadow;
- Waves(int _x, int _y, int _layerWidth, int _layerHeight) {
- x = _x; y = _y;
- layerWidth = _layerWidth; layerHeight = _layerHeight;
- xBound = random(5,15);
- yBound = random(10,15);
- xTheta = random(0.03,0.05);
- yTheta = random(0.02,0.1);
- make();
- }
- void make() {
- // create the wave cutouts
- wMask = createGraphics(layerWidth,layerHeight, P2D);
- int r = 0;
- wMask.beginDraw();
- wMask.background(255);
- wMask.noStroke();
- wMask.fill(0);
- for (int i = 0; i<layerWidth; i += r) {
- r = int(random(30,50));
- wMask.ellipse(i,0,r*2,r*2);
- }
- wMask.endDraw();
- // create the basic wave
- wave = createGraphics(layerWidth,layerHeight, P2D);
- wave.beginDraw();
- wave.fill(0,120,255);
- wave.noStroke();
- wave.rect(0,0,layerWidth,200);
- wave.endDraw();
- // cutout mask from wave
- wave.mask(wMask);
- // add drop shadow
- wShadow = createGraphics(layerWidth,layerHeight,P2D);
- wShadow.beginDraw();
- wShadow.copy(wave, 0, 0, layerWidth, layerHeight, 0, 0, layerWidth, layerHeight);
- wShadow.filter(THRESHOLD,1);
- wShadow.filter(BLUR, 4);
- wShadow.endDraw();
- }
- void update() {
- xMove = map(sin(frameCount*xTheta),0,1,-xBound,xBound);
- yMove = map(sin(frameCount*yTheta),0,1,-yBound,yBound);
- }
- void display() {
- image(wShadow,x+xMove,y+yMove);
- image(wave,x+xMove,y+yMove);
- }
- }
1