js计算matrix 实现transform

14 篇文章 0 订阅
8 篇文章 0 订阅
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            margin: auto;
            background: red;
            width: 400px;

        }
    </style>
</head>

<body>
    <div id='move-me' class='transformable'>
        <h2>Move me with a matrix</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
    </div>
</body>
<script>

    function mtrMultMtr(matrixA, matrixB) {

        let res = [];
        let b = 0;
        for (let k = 0; k < 16; k++) {
            let a = Math.floor(k / 4);
            let n = 0;

            for (let j = 0; j < 16; j += 4) {
                n += matrixA[a + j] * matrixB[b + j];
            }
            b++;
            if (b == 4) b = 0;
            res.push(n)
        }
        return res;
    }



    function scale(x, y, z) {
        return [
            x, 0, 0, 0,
            0, y, 0, 0,
            0, 0, z, 0,
            0, 0, 0, 1
        ];
    }
    function translate(x, y, z) {
        return [
            1, 0, 0, 0,
            0, 1, 0, 0,
            0, 0, 1, 0,
            x, y, z, 1
        ];
    }

    function rotate(x, y, z) {
        let mixMatrix =  mtrMultMtr( rotateX(x), rotateY(y));
        return  mtrMultMtr( mixMatrix, rotateZ(z));
    }
    function rotateX(a) {

        return [
            1, 0, 0, 0,
            0, Math.cos(a), -Math.sin(a), 0,
            0, Math.sin(a), Math.cos(a), 0,
            0, 0, 0, 1
        ];
    }

    function rotateY(a) {

        return [
            Math.cos(a), 0, Math.sin(a), 0,
            0, 1, 0, 0,
            -Math.sin(a), 0, Math.cos(a), 0,
            0, 0, 0, 1
        ];
    }

    function rotateZ(a) {

        return [
            Math.cos(a), -Math.sin(a), 0, 0,
            Math.sin(a), Math.cos(a), 0, 0,
            0, 0, 1, 0,
            0, 0, 0, 1
        ];
    }



    function matrixArrayToCssMatrix(array) {
        return "matrix3d(" + array.join(',') + ")";
    }

    const moveMe = document.body.querySelector('#move-me');
    const deg = Math.PI / 180;
    const matrix = mtrMultMtr(  scale(0.5,0.5, 1) , rotate(0, 0, 45 * deg));

    moveMe.style.transform = matrixArrayToCssMatrix(matrix)

</script>

</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值