使用Raphael创建一个简单的时钟

1次阅读

共计 1586 个字符,预计需要花费 4 分钟才能阅读完成。


最外边黑色的弧代表时针,中间的代表分针,最里面的代表秒针。
我们需要根据现在多少时间,计算出需要画多少的弧长,三条弧只是半径,颜色不一样,封装出一个函数就行,然后每秒执行一次这个函数画弧,画弧操作前面的文章已经说了 svg 的 path,这里不再唠叨。
这里主要解决每秒都画的话就会有很多个 path 堆积,不可能这么画,怎样再第一次的时候创建画好,后续不画,只修改数据

<!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>
    <script src="garage/raphael-master/raphael.js"></script>
    <style>
        body {background: rgb(236, 198, 29);
        }
    </style>
    <script>
        window.onload = function () {let paper = Raphael(0, 0, 800, 600);
            let cx = 400, cy = 300;

            function createPath(r, ang, color) {let path = paper.path();
                path.attr({
                    'stroke-width': 20,
                    'stroke': color
                })
                calc(ang, true);

                function calc(ang, isFirst = false) {// 计算弧
                    let arr = [];
                    arr.push(`M ${cx} ${cy - r}`);
                    let x = cx + Math.sin(ang * Math.PI / 180) * r;
                    let y = cy - Math.cos(ang * Math.PI / 180) * r;
                    arr.push(`A ${r} ${r} 0 ${ang > 180 ? 1 : 0} 1 ${x} ${y}`);

                    if (isFirst) {path.attr('path', arr.join(' '));
                    } else {if (ang == 0) {path.attr('path', arr.join(' '));
                        } else {path.animate({ path: arr.join('') }, 500,'bounce');
                        }
                    }
                }
                path.calc = calc;// 这个方法是为了后续画好后修改数据
                return path;
            }
            // 这部分是为了让 path 不重复创建,第一次创建,后续只需要修改就可以了
            let paths = []
            function tick() {let oDate = new Date();
                let hours = oDate.getHours() > 12 ? oDate.getHours() % 12 : oDate.getHours();// 如果时针到了 13 点,就置为 1 点
                if (paths.length == 0) {
                    paths = [createPath(200, 360 * hours / 12, 'rgb(54, 54, 54)'),
                        createPath(150, 360 * oDate.getMinutes() / 60, 'orange'),
                        createPath(100, 360 * oDate.getSeconds() / 60, 'white')
                    ]
                } else {paths[0].calc(360 * hours / 12);
                    paths[1].calc(360 * oDate.getMinutes() / 60);
                    paths[2].calc(360 * oDate.getSeconds() / 60);
                }
            }
            tick();// 初始化时先执行一次
            setInterval(tick, 1000)

        }
    </script>
</head>
<body>
</body>
</html>

正文完
 0