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

孤者浪人 提交于 2019-12-13 01:38:33

问题


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:


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.



来源:https://stackoverflow.com/questions/36989216/over-riding-the-background-function-in-p5-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!