Image Circle Distortion in p5js

I am trying to implement a circle distortion function in p5js. Here is an example of what I want to achieve:

Example

In the example an original image is distorted into a 2d circle with an inner and outer radius.

I have been trying to translate the code from the example into my p5js sketch, but I have had limited success.

Here is my code and the resulting image:

let img;
let cx;
let cy;
let innerRadius;
let outerRadius;
let startX;
let startY;
let endX;
let endY;

function preload() {
  img = loadImage('image.jpg');
}

function setup() {
  createCanvas(img.width, img.height);
  image(img, 0, 0);

  noLoop();

  cx = width / 2;
  cy = height / 2;
  innerRadius = 0;
  outerRadius = 320;
  startX = 0;
  startY = 0;
  endX = img.width;
  endY = img.height;
}

function draw() {
  let angle = 0;
  let step = 1 * atan2(1, outerRadius);
  let limit = 2 * PI;
  
  push();
  translate(cx, cy);
  while (angle < limit) {
    push();
    rotate(angle);
    translate(innerRadius, 0);
    rotate(-PI / 2);
    let ratio = angle / limit;
    let x = startX + ratio * (endX - startX);
    image(img, x, startY, 1, (endY - startY), 0, 0, 1, (outerRadius - innerRadius));
    pop();
    angle += step;
  }
  pop();
}

Result of code

Please is anyone able to tell me where I am going wrong?

Hello,
I have slightly modified your code below not for optimization but to get the concept working. I remove a push/pop call in your while loop and use rotate(angle); to make it more simple, in case you are wondering.
You need to fix the stitching of the beginning at final angle so it seems.

Original and resulting image below. Remark: white edges in original image is due to copy and paste in the forum but not present in the actual image.

Kf


//NOTE:
// SET deltaSlice to 1 in setup or any non-zero value. This is the slice from the source image

function draw() {

  push();
  translate(cx, cy);
  rotate(-Math.PI / 2.0);

  while (angle < limit ) {

    rotate(step);   
    angle += step;

    let ratio = angle / limit;
    let x = ratio * img.width;
    image(img, 0, 0, deltaSlice, outerRadius, x, 0, deltaSlice, height);
 
  }  //while

  pop();
}
1 Like

Thank you very much! I shall study your code in Web Editor later and see what happens …

Marking kfrajer’s post as the solution. Many thanks kfrajer!

After altering my code a desired result is produced:

1 Like