菜单
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP 如何 W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Canvas 时钟盘面


第二部分 - 绘制时钟盘面

时钟需要一个时钟盘面。创建一个 JavaScript 函数来绘制时钟盘面

JavaScript

function drawClock() {
  drawFace(ctx, radius);
}

function drawFace(ctx, radius) {
  const grad = ctx.createRadialGradient(0, 0 ,radius * 0.95, 0, 0, radius * 1.05);
  grad.addColorStop(0, '#333');
  grad.addColorStop(0.5, 'white');
  grad.addColorStop(1, '#333');

  ctx.beginPath();
  ctx.arc(0, 0, radius, 0, 2 * Math.PI);
  ctx.fillStyle = 'white';
  ctx.fill();

  ctx.strokeStyle = grad;
  ctx.lineWidth = radius*0.1;
  ctx.stroke();

  ctx.beginPath();
  ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI);
  ctx.fillStyle = '#333';
  ctx.fill();
}
自己动手试一试 »


代码解释

创建一个 drawFace() 函数来绘制时钟盘面

function drawClock() {
  drawFace(ctx, radius);
}

function drawFace(ctx, radius) {
}

绘制白色圆形

ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2 * Math.PI);
ctx.fillStyle = 'white';
ctx.fill();

创建一个径向渐变(原始时钟半径的 95% 和 105%)

grad = ctx.createRadialGradient(0, 0, radius * 0.95, 0, 0, radius * 1.05);

创建 3 个颜色停止点,对应于圆弧的内边缘、中间和外边缘

grad.addColorStop(0, '#333');
grad.addColorStop(0.5, 'white');
grad.addColorStop(1, '#333');

颜色停止点创建了 3D 效果。

将渐变定义为绘图对象的描边样式

ctx.strokeStyle = grad;

定义绘图对象的线宽(半径的 10%)

ctx.lineWidth = radius * 0.1;

绘制圆形

ctx.stroke();

绘制时钟中心

ctx.beginPath();
ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI);
ctx.fillStyle = '#333';
ctx.fill();

×

联系销售

如果您想将 W3Schools 服务用于教育机构、团队或企业,请发送电子邮件给我们
sales@w3schools.com

报告错误

如果您想报告错误,或想提出建议,请发送电子邮件给我们
help@w3schools.com

W3Schools 经过优化,旨在方便学习和培训。示例可能经过简化,以提高阅读和学习体验。教程、参考资料和示例会不断审查,以避免错误,但我们无法保证所有内容的完全正确性。使用 W3Schools 即表示您已阅读并接受我们的使用条款Cookie 和隐私政策

版权所有 1999-2024 Refsnes Data。保留所有权利。W3Schools 由 W3.CSS 提供支持