Media: Images

Load images and fit them into canvas space correctly.

Example 1: Scale to Fit

Code

let img;

function preload() {
  img = loadImage('../assets/images/map.jpg');
}

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(245);
  const pad = 20;
  const availW = width - pad * 2;
  const availH = height - pad * 2;
  const ratio = min(availW / img.width, availH / img.height);
  const w = img.width * ratio;
  const h = img.height * ratio;
  const x = (width - w) / 2;
  const y = (height - h) / 2;
  image(img, x, y, w, h);
}

Try this: Change padding to compare object-fit behavior.

Open sketch in new tab

Example 2: Tint Overlay

Code

let img;

function preload() {
  img = loadImage('../assets/images/map.jpg');
}

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(20);
  image(img, 0, 0, width, height);
  tint(255, 110, 180, 140);
  image(img, 0, 0, width, height);
  noTint();

  fill(255);
  text('Tinted overlay', 14, 24);
}

Try this: Toggle tint on key press for before/after comparison.

Open sketch in new tab

Resources