Skip to content

Commit

Permalink
transform images too
Browse files Browse the repository at this point in the history
  • Loading branch information
KTibow committed Dec 3, 2023
1 parent e6f018f commit 8828e30
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
2 changes: 1 addition & 1 deletion docs/03-plugins/apply-transforms-shapes.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ svgo:
defaultPlugin: true
---

Applies the `transform` attribute directly to `<circle>`, `<ellipse>`, and `<rect>` when possible.
Applies the `transform` attribute directly to `<circle>`, `<ellipse>`, `<rect>`, and `<image>` when possible.

## Usage

Expand Down
21 changes: 18 additions & 3 deletions plugins/applyTransformsShapes.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const { transformsMultiply, transform2js } = require('./_transforms.js');
exports.name = 'applyTransformsShapes';
exports.description = 'Applies transforms to some shapes.';

const APPLICABLE_SHAPES = ['circle', 'ellipse', 'rect'];
const APPLICABLE_SHAPES = ['circle', 'ellipse', 'rect', 'image'];

/**
* @typedef {number[]} Matrix
Expand All @@ -32,9 +32,9 @@ exports.fn = (root, params) => {

const computedStyle = computeStyle(stylesheet, node);
const transformStyle = computedStyle.transform;
if (!transformStyle) return;
if (
transformStyle.type === 'static' &&
!transformStyle ||
transformStyle.type !== 'static' ||
transformStyle.value !== node.attributes.transform
) {
return;
Expand Down Expand Up @@ -70,6 +70,11 @@ exports.fn = (root, params) => {
matrix.data[1] != 0 &&
matrix.data[2] != 0 &&
matrix.data[3] == 0);
const isTranslation =
matrix.data[0] == 1 &&
matrix.data[1] == 0 &&
matrix.data[2] == 0 &&
matrix.data[3] == 1;
const scale = Math.sqrt(
matrix.data[0] * matrix.data[0] + matrix.data[1] * matrix.data[1]
);
Expand Down Expand Up @@ -174,6 +179,16 @@ exports.fn = (root, params) => {
node.attributes.ry = stringifyNumber(newRy, factor, leadingZero);
else delete node.attributes.ry;
delete node.attributes.transform;
} else if (node.name == 'image') {
if (!isTranslation) return;

const x = Number(node.attributes.x || '0');
const y = Number(node.attributes.y || '0');
const corner = transformAbsolutePoint(matrix.data, x, y);

node.attributes.x = stringifyNumber(corner[0], factor, leadingZero);
node.attributes.y = stringifyNumber(corner[1], factor, leadingZero);
delete node.attributes.transform;
}
},
},
Expand Down

0 comments on commit 8828e30

Please sign in to comment.