发布于 2026-01-06 0 阅读
0

如何使用 JavaScript 和 SVG 构建时钟 DEV 的全球展示挑战赛,由 Mux 呈现:展示你的项目!

如何使用 JavaScript 和 SVG 构建时钟

由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!

JavaScript 是一种编程语言,可用于创建复杂的网页功能。另一方面,可缩放矢量图形 (SVG) 是一种基于可扩展标记语言 (XML) 的二维矢量图像格式,它支持交互性和动画效果。

因此,使用 SVG(标量矢量图形)和 JavaScript 构建时钟非常简单。

目录

  • JavaScript 入门。
  • 什么是SVG?
  • SVG 的优势。
  • 如何在网页上实现带有 SVG 的 JavaScript。
  • 资源。
  • 结论。

先决条件

  • 具备JavaScript基础知识。
  • 集成开发环境(例如 Visual Studio Code)。

JavaScript 入门

JavaScript 是一种编程语言,可用于创建复杂的应用程序。它还可用于创建具有动态样式、动画和其他功能的网页游戏,例如按钮按下或在表单中输入数据时触发的事件。

JavaScript 是一种功能强大的脚本语言。除了 JavaScript 核心语言之外,开发者还编写了许多工具,只需极少的投入就能解锁大量的功能。

这些工具包括:

  • 可与 HTML 一起使用的第三方框架和库,可加快应用程序的开发速度。
  • 第三方 API 允许开发者将来自其他内容提供商(例如 Twitter 或 Facebook)的功能集成到他们的网站中。
  • 浏览器应用程序编程接口(API)是内置于网络浏览器中的功能,允许您访问不同的功能。

什么是SVG

SVG是Scalable Vector Graphics(可缩放矢量图形)的缩写。这是一种XML格式,用于定义基于矢量图形的图形。

SVG 类型

  • HTML中的SVG
  <!DOCTYPE html>
  <html>
    <body>
      <h1>My first SVG</h1>

      <svg width="100" height="100">
        <circle
          cx="50"
          cy="50"
          r="40"
          stroke="green"
          stroke-width="4"
          fill="yellow"
        />
      </svg>
    </body>
  </html>
Enter fullscreen mode Exit fullscreen mode
  • SVG矩形
    <svg width="400" height="110">
        <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
    </svg>
Enter fullscreen mode Exit fullscreen mode
  • SVG 圆形
    <svg height="100" width="100">
        <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
    </svg>
Enter fullscreen mode Exit fullscreen mode
  • SVG椭圆
    <svg height="140" width="500">
        <ellipse cx="200" cy="80" rx="100" ry="50"
        style="fill:yellow;stroke:purple;stroke-width:2" />
    </svg>
Enter fullscreen mode Exit fullscreen mode
  • SVG 线条
    <svg height="210" width="500">
        <line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2" />
    </svg>
Enter fullscreen mode Exit fullscreen mode
  • SVG 多边形
    <svg height="210" width="500">
        <polygon points="200,10 250,190 160,210" style="fill:lime;stroke:purple;stroke-width:1" />
    </svg>
Enter fullscreen mode Exit fullscreen mode
  • SVG折线
    <svg height="200" width="500">
        <polyline points="20,20 40,25 60,40 80,120 120,140 200,180"
        style="fill:none;stroke:black;stroke-width:3" />
    </svg>
Enter fullscreen mode Exit fullscreen mode
  • SVG路径
    <svg height="210" width="400">
        <path d="M150 0 L75 200 L225 200 Z" />
    </svg>
Enter fullscreen mode Exit fullscreen mode
  • SVG文本
    <svg height="30" width="200">
        <text x="0" y="15" fill="red">I love SVG!</text>
    </svg>
Enter fullscreen mode Exit fullscreen mode
  • SVG描边
  <svg height="80" width="300">
    <g fill="none">
    <path stroke="red" d="M5 20 l215 0" />
    <path stroke="black" d="M5 40 l215 0" />
    <path stroke="blue" d="M5 60 l215 0" />
    </g>
  </svg>
Enter fullscreen mode Exit fullscreen mode
  • SVG模糊效果
        <svg height="110" width="110">
            <defs>
                <filter id="f1" x="0" y="0">
                <feGaussianBlur in="SourceGraphic" stdDeviation="15" />
                </filter>
            </defs>
            <rect width="90" height="90" stroke="green" stroke-width="3"
            fill="yellow" filter="url(#f1)" />
        </svg>
Enter fullscreen mode Exit fullscreen mode
  • SVG阴影
        <svg height="120" width="120">
            <defs>
                <filter id="f1" x="0" y="0" width="200%" height="200%">
                    <feOffset result="offOut" in="SourceGraphic" dx="20" dy="20" />
                    <feBlend in="SourceGraphic" in2="offOut" mode="normal" />
                </filter>
            </defs>
            <rect width="90" height="90" stroke="green" stroke-width="3"
        fill="yellow" filter="url(#f1)" />
        </svg>
Enter fullscreen mode Exit fullscreen mode
  • SVG线性
        <svg height="150" width="400">
            <defs>
                <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
                <stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
                <stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
                </linearGradient>
            </defs>
            <ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad1)" />
        </svg>
Enter fullscreen mode Exit fullscreen mode
  • SVG径向
    <svg height="150" width="500">
        <defs>
            <radialGradient id="grad1" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
            <stop offset="0%" style="stop-color:rgb(255,255,255);
            stop-opacity:0" />
            <stop offset="100%" style="stop-color:rgb(0,0,255);stop-opacity:1" />
            </radialGradient>
        </defs>
        <ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad1)" />
    </svg>
Enter fullscreen mode Exit fullscreen mode

SVG的优势

以下是使用 SVG 相对于其他图像格式(例如 JPEG 和 GIF)的一些优势:

  • 任何文本编辑器都可以用来生成和编辑 SVG 文件。
  • 可以查找、索引、编写脚本和压缩 SVG 格式的照片。
  • SVG图像可以缩放到任意大小。
  • SVG图像可以以任意比例进行高分辨率打印。
  • SVG 图像可以放大和缩小。
  • SVG 图形放大或调整大小时不会损失质量。
  • SVG是免费的。
  • SVG 文件完全由 XML 构成。

如何在网页上实现带有 SVG 的 JavaScript

现在,让我们使用 JavaScript 和上面提到的一个 SVG 示例,创建一个简单的网页来开发一个网页时钟。

步骤 1 - 打开您的集成开发环境 (IDE)。

要打开 Visual Studio Code,请导航到计算机上任意目录,然后在终端中输入:

code.
Enter fullscreen mode Exit fullscreen mode

注意:code .如果您的系统上没有安装 Visual Studio Code,则此方法无效。

步骤 2 - 生成文件

输入以下命令创建 index.html、style.css 和 script.js 文件:

  • Windows PowerShell
    ni index.html,style.css,script.js
Enter fullscreen mode Exit fullscreen mode
  • Linux
  touch index.html,style.css,script.js
Enter fullscreen mode Exit fullscreen mode

步骤 3 - 向 index.html 添加基本的 HTML 代码片段

在 index.html 文件中,我们需要设置一个基本的 html 页面,其中包含以下代码片段:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>How to Build a Clock with JavaScript and SVG</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
  </head>
  <body>
    <main class="main">
      <!-- clockbox -->
    </main>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

步骤 4 - 引用 style.css 和 script.js 文件

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>How to Build a Clock with JavaScript and SVG</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" type="text/css" media="screen" href="style.css" /> <--css reference--!>
  </head>
  <body>
    <main class="main">
      <!-- clockbox -->
    </main>

    <script src="script.js"></script> <--js reference--!>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

是的,我们准备开始了;希望你们都能跟上。😊

步骤 6 - 将 SVG 添加到 index.html

由于我们要制作一个时钟,我们需要 svg 圆形和 svg 路径来表示指针,如下所示。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>How to Build a Clock with JavaScript and SVG</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" type="text/css" media="screen" href="style.css" />
  </head>
  <body>
    <h1>How to Build a Clock with JavaScript and SVG</h1>
    <main class="main">
      <div class="clockbox">
        <svg
          id="clock"
          xmlns="http://www.w3.org/2000/svg"
          width="300"
          height="200"
          viewBox="0 0 600 600"
        >
          <g id="face">
            <circle class="circle" cx="300" cy="300" r="253.9" />
            <path
              class="hour-marks"
              d="M300.5 94V61M506 300.5h32M300.5 506v33M94 300.5H60M411.3 107.8l7.9-13.8M493 190.2l13-7.4M492.1 411.4l16.5 9.5M411 492.3l8.9 15.3M189 492.3l-9.2 15.9M107.7 411L93 419.5M107.5 189.3l-17.1-9.9M188.1 108.2l-9-15.6"
            />
            <circle class="mid-circle" cx="300" cy="300" r="16.2" />
          </g>
          <g id="hour">
            <path class="hour-arm" d="M300.5 298V142" />
            <circle class="sizing-box" cx="300" cy="300" r="253.9" />
          </g>
          <g id="minute">
            <path class="minute-arm" d="M300.5 298V67" />
            <circle class="sizing-box" cx="300" cy="300" r="253.9" />
          </g>
          <g id="second">
            <path class="second-arm" d="M300.5 350V55" />
            <circle class="sizing-box" cx="300" cy="300" r="253.9" />
          </g>
        </svg>
      </div>
      <!-- .clockbox -->
    </main>

    <script src="script.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

你有没有注意到现在所有标签都有一个id和一个class?我们将使用这些id作为设计和JavaScript的参考点。

步骤 7 - 实现时钟的 JavaScript 代码

现在是时候开始编写一些 JavaScript 代码了。下面展示并解释了此 Web 应用程序的核心功能以及 JavaScript 代码和时间配置。

// Declare and Initialize your variables and make references to the id defined in the html file, as needed.
const HOURHAND = document.querySelector("#hour");
const MINUTEHAND = document.querySelector("#minute");
const SECONDHAND = document.querySelector("#second");

// Declare and Initialize the inbuilt date function
const date = new Date();

//
let hr = date.getHours();
let min = date.getMinutes();
let sec = date.getSeconds();

// Log to see the output in the console
console.log("Hour: " + hr + " Minute: " + min + " Second: " + sec);
Enter fullscreen mode Exit fullscreen mode

步骤 8 - 实施职位

现在让我们实现(小时,分钟,秒)的位置,因为我们现在可以在控制台中看到输出。

// Declare and Initialize your variables and create positions for each.
let hrPosition = (hr * 360) / 12 + (min * (360 / 60)) / 12;
let minPosition = (min * 360) / 60 + (sec * (360 / 60)) / 60;
let secPosition = (sec * 360) / 60;

// Create a function that actually run the clock
const runClock = () => {
  // Set each position when the function is called
  hrPosition = hrPosition + 3 / 360;
  minPosition = minPosition + 6 / 60;
  secPosition = secPosition + 6;

  // Set the transformation for each arm
  HOURHAND.style.transform = "rotate(" + hrPosition + "deg)";
  MINUTEHAND.style.transform = "rotate(" + minPosition + "deg)";
  SECONDHAND.style.transform = "rotate(" + secPosition + "deg)";
};

// Use the inbuilt setInterval function to invoke the method we created earlier
setInterval(runClock, 1000);
Enter fullscreen mode Exit fullscreen mode

步骤 9 - 在 style.css 中添加样式

我们快完成了😊。

接下来我们去 style.css 文件完成剩下的任务。

body {
  color: black;
  background-color: rgb(94, 241, 119);
}

h1 {
  position: flex;
  text-align: center;
  font-style: normal;
  font-family: "Trebuchet MS", "Lucida Sans Unicode", "Lucida Grande",
    "Lucida Sans", Arial, sans-serif;
}

footer {
  text-align: center;
}

/* Layout */
.main {
  display: flex;
  padding: 1em;
  height: 80vh;
  justify-content: center;
  align-items: middle;
}

.clockbox,
#clock {
  width: 100%;
  height: 100%;
}

/* Clock styles */
.circle {
  fill: none;
  stroke: #000;
  stroke-width: 9;
  stroke-miterlimit: 10;
}

.mid-circle {
  fill: #000;
}

.hour-marks {
  fill: none;
  stroke: #000;
  stroke-width: 9;
  stroke-miterlimit: 10;
}

.hour-arm {
  fill: none;
  stroke: #000;
  stroke-width: 17;
  stroke-miterlimit: 10;
}

.minute-arm {
  fill: none;
  stroke: #000;
  stroke-width: 11;
  stroke-miterlimit: 10;
}

.second-arm {
  fill: none;
  stroke: #000;
  stroke-width: 4;
  stroke-miterlimit: 10;
}

/* Transparent box ensuring arms center properly. */
.sizing-box {
  fill: none;
}

/* Make all arms rotate around the same center point. */
/* Optional: Use transition for animation. */
#hour,
#minute,
#second {
  transform-origin: 300px 300px;
  transition: transform 0.5s ease-in-out;
}
Enter fullscreen mode Exit fullscreen mode

步骤 10 - 测试应用程序

要体验神奇效果,请启动您的实时服务器或在浏览器中预览应用程序,如下所示。

image.png

恭喜🎉🎉

请点击下方链接查看 CodePen 示例:

资源

结论

本文介绍了 JavaScript、SVG 的概念、SVG 的优势以及如何在网页上使用 JavaScript 和 SVG。
此外,还重点介绍了几种 SVG 类型及其在网页上的应用。

祝您编程愉快!

您可以通过推特联系我。

文章来源:https://dev.to/olanetsoft/how-to-build-a-clock-with-javascript-and-svg-4578