Skip to content

svgTranslateBy function ​

An order of applySvgTransforms that moves the element along its own axes, in its own units: turned by 90°, "to the right" goes down on screen. After svgRotateTo(0) and svgFlipTo(false), its axes are those of the screen.

ts
import { svgTranslateBy } from 'utils';

Signature ​

ts
export function svgTranslateBy(dx: number, dy: number): SvgTransformOrder<[dx: number, dy: number]>

Parameters ​

NameDescription
dxThe distance along its width.
dyThe distance along its height.

Returns ​

The order, to change with set(dx, dy).

Example ​

ts
const position = svgTranslateBy(0, 0);
applySvgTransforms(train, [position]);
position.set(10, 0); // 10 units forward, where the train points

Tests ​

Line coverage: 100 %.

  • ✅ moves along the axes of the element

Source ​

src/svg-transform/svg-translate-by.ts (on GitHub)

Uses ​

  • SvgTransformOrder: An order of applySvgTransforms, created by svgRotateBy, svgRotateTo, svgFlipTo, svgScaleBy, svgTranslateBy or svgPlaceOn: keep it to change its values later with set.

Files it needs ​

src/svg-transform/svg-translate-by.ts imports, directly or not:

Source code
ts
import { createMatrix, createOrder, inOwnAxes } from './internal';
import type { SvgTransformOrder } from './svg-transform-order';

/**
 * An order of `applySvgTransforms` that moves the element along its own axes, in its own units: turned by
 * 90°, "to the right" goes down on screen. After `svgRotateTo(0)` and `svgFlipTo(false)`, its axes are those of
 * the screen.
 *
 * @param dx - The distance along its width.
 * @param dy - The distance along its height.
 * @returns The order, to change with `set(dx, dy)`.
 * @example
 * const position = svgTranslateBy(0, 0);
 * applySvgTransforms(train, [position]);
 * position.set(10, 0); // 10 units forward, where the train points
 */
export function svgTranslateBy(dx: number, dy: number): SvgTransformOrder<[dx: number, dy: number]> {
  return createOrder([dx, dy], (element, screen, x, y) => inOwnAxes(screen, createMatrix(element).translate(x, y)));
}
Test file
ts
import { applySvgTransforms } from './apply-svg-transforms';
import { svgTranslateBy } from './svg-translate-by';
import { describeOnScreen, renderSvg } from './testing';

describe(svgTranslateBy, () => {
  it('moves along the axes of the element', () => {
    const byId = renderSvg('<rect id="train" transform="translate(100 100) rotate(90)" width="10" height="10" />');
    applySvgTransforms(byId('train'), [svgTranslateBy(10, 0)]);
    expect(describeOnScreen(byId('train'))).toMatchObject({ x: 90, y: 110 });
  });
});

Keywords: svg, translate, by, svg transforms, function

Generated from the JSDoc of the sources.