Skip to content

Instantly share code, notes, and snippets.

@milansav
Created July 26, 2022 09:05
Show Gist options
  • Save milansav/f903e37941aebf15577db47b86fa802f to your computer and use it in GitHub Desktop.
Save milansav/f903e37941aebf15577db47b86fa802f to your computer and use it in GitHub Desktop.
CSS Clip path scale & transformation matrix
const translationMatrix = (x, y) => {
return [
[1, 0, x],
[0, 1, y],
[0, 0, 1]
];
};
const scalingMatrix = (sx, sy) => {
return [
[sx, 0, 0],
[0, sy, 0],
[0, 0, 1]
];
};
const point = [
0.25,
0.05,
0
];
function multiplyVectorByMatrix(v, m) {
const x = v[0]*m[0][0] + v[1]*m[1][0] + v[2]*m[2][0];
const y = v[0]*m[0][1] + v[1]*m[1][1] + v[2]*m[2][1];
const z = v[0]*m[0][2] + v[1]*m[1][2] + v[2]*m[2][2];
return [x, y, z];
}
class Matrix {
constructor(value) {
this.value = value;
}
multiplyByMatrix(m) {
const c1 = (this.value[0][0] * m[0][0]) + (this.value[0][1] * m[1][0]) + (this.value[0][2] * m[2][0]);
const c2 = (this.value[0][0] * m[0][1]) + (this.value[0][1] * m[1][1]) + (this.value[0][2] * m[2][1]);
const c3 = (this.value[0][0] * m[0][2]) + (this.value[0][1] * m[1][2]) + (this.value[0][2] * m[2][2]);
const c4 = (this.value[1][0] * m[0][0]) + (this.value[1][1] * m[1][0]) + (this.value[1][2] * m[2][0]);
const c5 = (this.value[1][0] * m[0][1]) + (this.value[1][1] * m[1][1]) + (this.value[1][2] * m[2][1]);
const c6 = (this.value[1][0] * m[0][2]) + (this.value[1][1] * m[1][2]) + (this.value[1][2] * m[2][2]);
const c7 = (this.value[2][0] * m[0][0]) + (this.value[2][1] * m[1][0]) + (this.value[2][2] * m[2][0]);
const c8 = (this.value[2][0] * m[0][1]) + (this.value[2][1] * m[1][1]) + (this.value[2][2] * m[2][1]);
const c9 = (this.value[2][0] * m[0][2]) + (this.value[2][1] * m[1][2]) + (this.value[2][2] * m[2][2]);
const result = [
[c1, c2, c3],
[c4, c5, c6],
[c7, c8, c9]
];
this.value = result;
return this;
}
Matrix() {
return this.value;
}
}
const input = "50% 5%, 150% 5%, 200% 50%, 150% 95%, 50% 95%, 0% 50%";
console.log(input);
let points = input.replace(/%/g, "").split(", ").map(array => {let b = array.split(" "); b = b.map(item => parseInt(item)/100); b.push(0); return b;});
const m = new Matrix(translationMatrix(-0.5, -0.5)).multiplyByMatrix(scalingMatrix(0.5, 0.5)).multiplyByMatrix(translationMatrix(0.5, 0.5));
let newPoints = [];
points = points.map(point => {
newPoints.push(multiplyVectorByMatrix(point, m.Matrix()));
});
console.log(newPoints.map(array => array.map(element => (element*100).toString() + "%").slice(0, 2).join(" ")).join(", "));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment