Skip to content

Three Points Affine Distortion

In this example we will apply 3-points affine distortion to the following image:

Test table

Apply affine distortion with 3 control points (apply scaling, rotation, translation and shearing):

ts
import {
  Canvas,
  distortUnwrap,
  makeCanvas,
  VirtualPixelMethod,
} from "@alxcube/lens";

// Load source image
const sourceImage = await Canvas.createFromUrl("test-table.jpg");

const controlPoints = [0, 0, 80, 50, 100, 0, 125, 80, 0, 100, 70, 100];
const image = await distortUnwrap(sourceImage, "Affine", controlPoints, {
  imageBackgroundColor: "#ff0",
  virtualPixelMethod: VirtualPixelMethod.BACKGROUND,
});

// Display result
const canvas = makeCanvas(image.width, image.height, true);
canvas.getContext("2d").drawImage(image, 0, 0);
document.body.appendChild(canvas);

Result without best fit

I set virtual pixels to yellow color for better understanding output image size.

And now apply the same transform, but with bestFit option:

ts
import {
  Canvas,
  distortUnwrap,
  makeCanvas,
  VirtualPixelMethod,
} from "@alxcube/lens";

// Load source image
const sourceImage = await Canvas.createFromUrl("test-table.jpg");

const controlPoints = [0, 0, 80, 50, 100, 0, 125, 80, 0, 100, 70, 100];
const image = await distortUnwrap(sourceImage, "Affine", controlPoints, {
  imageBackgroundColor: "#ff0",
  virtualPixelMethod: VirtualPixelMethod.BACKGROUND,
  viewport: "bestFit", 
});

// Display result
const canvas = makeCanvas(image.width, image.height, true);
canvas.getContext("2d").drawImage(image, 0, 0);
document.body.appendChild(canvas);

We will get following result:

Result with best fit