Skip to content

Arc text

Following example show how we can make arc'ed text.

Source images:

Regular text: Regular text

Text, rotated 180 degrees: 180deg text

use following code to arc text to different angles:

ts
import { Canvas, distortUnwrap, type ImageAdapter } from "@alxcube/lens";

// Load source images with text
const [sourceText, sourceText360] = await Promise.all(
  ["arc-text-source.png", "arc-text-source-180.png"].map((url) =>
    Canvas.createFromUrl(url)
  )
);

// Function to make arc'ed text and draw it on canvas.
const makeArc = async (
  image: ImageAdapter<OffscreenCanvas | HTMLCanvasElement>,
  angle: number,
  rotate = 0
): Promise<HTMLCanvasElement> => {
  // Distort image using distortUnwrap to get underlying image OffscreenCanvas.
  const distorted = await distortUnwrap(image, "Arc", [angle, rotate]);

  // Create canvas element to draw result on
  const canvas = document.createElement("canvas");
  canvas.width = distorted.width;
  canvas.height = distorted.height;
  const context = canvas.getContext("2d");
  // Fill canvas with black since text is white and may not be visible on white background
  context.fillStyle = "#000";
  context.fillRect(0, 0, canvas.width, canvas.height);
  context.drawImage(distorted, 0, 0);
  return canvas;
};

const angles = [30, 90, 180, 360];

// Create text arc from regular text image for given angles and attach it to body
for (const angle of angles) {
  const canvas = await makeArc(sourceText, angle, 0);
  document.body.appendChild(canvas);
}

// Create text arc from rotated text image for given angles and attach it to body
for (const angle of angles) {
  const canvas = await makeArc(sourceText360, angle, 180);
  document.body.appendChild(canvas);
}

We get following results:

  • For regular text:
    • 30 deg angle: Regular 30 deg
    • 90 deg angle: Regular 90 deg
    • 180 deg angle: Regular 180 deg
    • 360 deg angle: Regular 360 deg
  • For 180 deg rotated text:
    • 30 deg angle: Regular 30 deg
    • 90 deg angle: Regular 90 deg
    • 180 deg angle: Regular 180 deg
    • 360 deg angle: Regular 360 deg