createGraphics as background image

Hey frens,

I generate a grid in setup-function and want to keep this as background- image in draw.
Here some code:

let img;
var scl = 30;
var cols, rows;
function setup() {
  

  createCanvas(400, 400);
    
  img = createGraphics(width, height);
  img.stroke(238, 238, 238);
  cols = floor(width / scl);
  rows = floor(height / scl);
  var yoff = 0;
  for (var y = 0; y < rows; y++) {
    var xoff = 0;
    for (var x = 0; x < cols; x++) {
      img.noFill();
      img.rect(x * scl, y * scl, scl, scl);
      push();
      translate(x * scl, y * scl);
      pop();

    }

  }
}

function draw() {
  background(img);
}

unfortunately it does not work.

Thanks for any advice in advance,
T

background only supports image outside of the various color formats you can read about it here

so you need to cast your p5.graphics to a p5.image and apparently the below snippet is the best method we have as far as i have read

img.copy(tmp, 0, 0, tmp.width, tmp.height, 0, 0, tmp.width, tmp.height);

you can see it in action in the code below

let img;
var scl = 20;
var cols, rows;

function setup() {
  createCanvas(400, 400);
  
  img = createImage(width, height);
  
  let tmp = createGraphics(width, height);
  tmp.stroke(238, 238, 238);
  cols = floor(width / scl);
  rows = floor(height / scl);
  for (var y = 0; y < rows; y++) {
    for (var x = 0; x < cols; x++) {
      tmp.fill(random(255));
      tmp.rect(x * scl, y * scl, scl, scl);
    }
  }
  img.copy(tmp, 0, 0, tmp.width, tmp.height, 0, 0, tmp.width, tmp.height);
}

function draw() {
  background(img);
}

why? idk design choices? createGraphics is basically createCanvas as it creates basically the same thing but it would have been nice if they introduced a toImage method into p5.graphics (and maybe they have?) anyways best of luck

1 Like

Both background() & set() are incompatible w/ datatype p5.Graphics in p5js.

Obviously that’s a flawed design oversight b/c in Processing’s Java Mode its PGraphics is a subclass of PImage; so everything works smoothly as it should.

As a workaround you could just use image() instead: image(img, 0, 0);

1 Like