postcss-css-matrixify
v1.0.1
Published
A PostCSS plugin that converts CSS transform functions to matrix form for optimized animations and transforms
Maintainers
Readme
postcss-css-matrixify
一个将 CSS 变换函数转换为矩阵形式的 PostCSS 插件,用于优化动画和变换效果。
特性
- 🔄 将 CSS 变换函数(
scale、rotate、translate、skew)转换为矩阵形式 - ⚡ 通过预计算变换矩阵优化动画性能
- 🎯 支持外部 CSS 文件和 HTML 内联样式
- 🧮 高精度处理 2D 变换
- 🛠️ 轻松集成 webpack 和其他构建工具
安装
npm install postcss-css-matrixify
# 或者
yarn add postcss-css-matrixify使用方法
与 PostCSS 一起使用
const postcss = require("postcss");
const matrixify = require("postcss-css-matrixify");
postcss([matrixify()])
.process(css, { from: "input.css", to: "output.css" })
.then((result) => {
console.log(result.css);
});与 Webpack 一起使用
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
"style-loader",
"css-loader",
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [require("postcss-css-matrixify")()],
},
},
},
],
},
],
},
};与 Vite 一起使用
// vite.config.js
import { defineConfig } from "vite";
export default defineConfig({
css: {
postcss: {
plugins: [require("postcss-css-matrixify")()],
},
},
});示例
输入
.element {
transform: scale(1.2) rotate(45deg) translate(100px, 50px);
}
.another-element {
transform: translateX(50px) translateY(-20px) rotateZ(0.1turn);
}输出
.element {
transform: matrix3d(
0.848528,
0.848528,
0,
0,
-0.848528,
0.848528,
0,
0,
0,
0,
1,
0,
100,
50,
0,
1
);
}
.another-element {
transform: matrix3d(
0.809017,
-0.587785,
0,
0,
0.587785,
0.809017,
0,
0,
0,
0,
1,
0,
50,
-20,
0,
1
);
}支持的变换函数
已支持(2D 变换)
- ✅
translate(x, y) - ✅
translateX(x) - ✅
translateY(y) - ✅
scale(x, y) - ✅
scaleX(x) - ✅
scaleY(y) - ✅
rotate(angle) - ✅
rotateZ(angle) - ✅
skew(x, y) - ✅
skewX(x) - ✅
skewY(y) - ✅
matrix(a, b, c, d, e, f) - ✅
translate3d(x, y, z)(忽略 Z 轴,转换为 2D) - ✅
scale3d(x, y, z)(忽略 Z 轴,转换为 2D) - ✅
rotate3d(0, 0, 1, angle)(仅支持 Z 轴旋转)
不支持(3D 变换)
- ❌
translateZ(z) - ❌
scaleZ(z) - ❌
rotateX(angle) - ❌
rotateY(angle) - ❌
rotate3d(x, y, z, angle)(除 Z 轴外) - ❌
matrix3d()(作为输入) - ❌
perspective()
配置
目前插件无需配置即可工作。未来版本可能包含以下选项:
- 自定义精度设置
- 3D 变换支持
- 性能优化选项
浏览器支持
生成的矩阵变换支持以下浏览器:
- Chrome 36+
- Firefox 16+
- Safari 9+
- Edge 12+
- iOS Safari 9+
- Android Browser 4.4+
为什么使用矩阵变换?
性能优势
- 减少重绘: 浏览器可以直接使用预计算的矩阵,无需重新计算多个变换函数
- GPU 加速: 矩阵变换更容易被 GPU 优化处理
- 动画流畅: 减少了动画过程中的计算负担
兼容性优势
- 跨浏览器一致性: 矩阵形式在不同浏览器中行为更一致
- 向后兼容: 支持更多老版本浏览器
许可证
MIT © wceozl
致谢
- 感谢 transformation-matrix 库提供的矩阵计算功能
- 感谢 PostCSS 社区提供的优秀插件生态系统
