Over-riding the background() function in p5.js?

2019-08-12 03:02发布

I made a galaxy sketch in p5.js using rotates and radians, but it's erased each time the background() is loaded as draw() runs. Is there a way to over-ride the background() function? I want the galaxies to remain in view.

 var stars;

function preload(){
//for (var i = 0; i < planetArray.length; i++) {
//stars = loadImage('Assets/stars.png');
}

function setup(){
  createCanvas(windowWidth, windowHeight);

}
function draw() {
  //background(0);
  star()
  //function mousepressed(){
}
  function star(){
  //angle = map(mouseX, 0,width, 0,360);
  //rotate(radians(angle*100));  
  noStroke();
  //translate(width/2, height/2);
  translate(mouseX,mouseY);
  fill(0);
  rotate(radians(frameCount%360)); //rotates output of ellipses
  rotate(radians(1000*frameCount%360));
  for(var i =0; i < 20; i++){
    push();
    noStroke();
    fill(random(200),0,random(150),random(2));
   // fill(random(125),random(250),random(100));
    ellipse(10*frameCount % (width/10),0,10,10);
    //image(stars, 10*frameCount % (width/2),0,10,10)
    //image((10*frameCount % (width/2),0,10,10)
    //
    pop();
  }
}

1条回答
Animai°情兽
2楼-- · 2019-08-12 03:43

Well, there really isn't any magic to it. Calling the background() function fills the window with a solid color (or image) and draws over anything you've previously drawn.

The solution to this problem isn't to "over-ride" the background() function. It's to restructure your program so your stuff gets drawn properly. Exactly how you do that depends on exactly what you want to happen.

Option 1: Only call the background() function once.

If you just want a black background at the beginning, and everything you do from the draw() function should still add up, then maybe you just want to call the background() function once. You could do it as the last line in your setup() function, for example.

Option 2: Store everything you want to draw in a data structure.

This is probably the most typical case. If you want a background to be drawn behind shapes that are moving around, you're going to have to store those shapes in some kind of data structure, and then draw all of them every single frame.

Option 3: Draw to an off-screen image, and then draw that image on top of your background.

This is a bit of a mix between the first two options. You can draw everything (except the background) to an off-screen PImage, and then draw the background to the screen, then draw the image to the screen. This allows you to have a background that changes colors without having to redraw everything else.

Which option you choose really depends on exactly what you want to happen.

查看更多
登录 后发表回答