如何用JavaScript和SVG构建一个时钟
JavaScript是一种编程语言,可以让你创建复杂的网页功能。另一方面,可扩展矢量图形(SVG)是一种基于可扩展标记语言(XML)的二维矢量图像格式。它支持互动性和动画。
因此,使用SVG(Scalar Vector Graphics)和JavaScript建立一个时钟是非常简单的。
目录
- JavaScript简介。
- 什么是SVG。
- SVG的好处。
- 如何在网络上用SVG实现JavaScript。
- 资源。
- 总结。
前提条件
- 对JavaScript的基本了解。
- 集成开发环境(如Visual studio代码)。
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> -
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> -
SVG 圆形
<svg height="100" width="100"> <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /> </svg> -
SVG 椭圆
<svg height="140" width="500"> <ellipse cx="200" cy="80" rx="100" ry="50" style="fill:yellow;stroke:purple;stroke-width:2" /> </svg> -
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> -
SVG多边形
<svg height="210" width="500"> <polygon points="200,10 250,190 160,210" style="fill:lime;stroke:purple;stroke-width:1" /> </svg> -
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> -
SVG 路径
<svg height="210" width="400"> <path d="M150 0 L75 200 L225 200 Z" /> </svg> -
SVG文本
<svg height="30" width="200"> <text x="0" y="15" fill="red">I love SVG!</text> </svg> -
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> -
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> -
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> -
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> -
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>
SVG的好处
以下是使用SVG比其他图像格式(如JPEG和GIF)的一些好处。
- 任何文本编辑器都可以用来生成和编辑SVG文件。
- SVG格式的照片可以被查找、索引、脚本化和压缩。
- SVG图像可以被缩放到任何尺寸。
- SVG图像可以在任何比例下以高分辨率打印。
- SVG中的图像可以被放大和缩小。
- 当SVG图形被放大或调整大小时,它们不会失去质量。
- SVG是免费的。
- SVG文件完全是由XML组成的。
如何在网络上用SVG实现JavaScript
现在,使用JavaScript和上面的一个SVG例子,让我们创建一个简单的网页,在网上开发一个时钟。
第1步 - 打开你的集成开发环境(IDE)。
要打开visual studio代码,请在你的电脑上导航到任何你选择的目录,在终端中输入。
code.
注意:如果你的系统上没有安装visual studio code,
code .,就不能工作。
第2步 - 生成文件
创建index.html、style.css和script.js,通过输入以下命令。
- Windows power shell
ni index.html,style.css,script.js
-
Linux
touch index.html,style.css,script.js
第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>
第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>
是的,我们已经准备好开始了;我希望你能跟上。 😊
第5步 - 在index.html中添加SVG
因为我们要建立一个时钟,所以我们需要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>Section Engineering: 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>
你有没有注意到,现在所有的标签都有一个id和一个class?我们将使用这些id作为我们设计和JavaScript的参考点。
第6步 - 实现时钟的JavaScript代码
现在是时候开始写一些JavaScript代码了。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);
第7步 - 实现位置
现在让我们来实现(hr, min sec)的位置,因为我们现在可以在控制台中看到输出。
// 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);
第8步 - 在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;
}
第9步 - 测试应用程序
要看到神奇的效果,请启动你的实时服务器或在你的浏览器中预览应用程序,如下所示。

恭喜你 🎉
总结
在这篇文章中,你了解了JavaScript,SVG是什么,SVG的好处,以及如何在网络上使用JavaScript与SVG。还强调了一些SVG类型,以及如何在网络上使用它们。