gpt4 book ai didi

javascript - 用 html canvas 构建一个时钟

转载 作者:行者123 更新时间:2023-11-28 16:28:37 25 4
gpt4 key购买 nike

我想使用 HTML5、canvas 和 JavaScript 创建一个时钟。但是我不明白为什么当我用 Sublime 运行以下代码时我什么也看不到。我尝试同时使用 Internet Explorer 和 Google Chrome 查看内容。也许错误在代码中?

这是我的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Clock</title>
<!--<script src="clockJS.js" ></script>-->
</head>
<body>

<canvas id="canvas" width="500" height="500"></canvas>
<img id="myImage" />
<script>

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
ctx.strokeStyle = '28d1fa';
ctx.linewidth = 17;
ctx.lineCap = "round";
ctx.shadowBlur = 15;
ctx.shadowColor = '28d1fa';

function degToRad(degree) {
var factor = Math.PI / 180;
return degree * factor;
}

function renderTime() {
var now = new Date();
var today = now.toDateString();
var time = today.toLocaleTimeString();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var milliseconds = now.getMilliseconds();
var newSeconds = seconds + (milliseconds/1000);

//Background
gradient = ctx.createRadioGradient(250, 250, 5, 250, 250, 300);
gradient.addColorStop(0, '09303a');
gradient.addColorStop(1, 'black');
ctx.fillStyle = gradient;
//ctx.fillStyle = '333333';
ctx.fillRect(0, 0, 500, 500);

//Hours
ctx.beginPath();
ctx.arc(250, 250, 200, degToRad(270), degToRad((hours*15)-90));
ctx.stroke();

//Minutes
ctx.beginPath();
ctx.arc(250, 250, 170, degToRad(270), degToRad((minutes*6)-90));
ctx.stroke();

//Seconds
ctx.beginPath();
ctx.arc(250, 250, 140, degToRad(270), degToRad((newSeconds*6)-90));
ctx.stroke();

//Date
ctx.font = "23px Arial bold";
ctx.fillStyle = '28d1fa';
ctx.fillText(today, 175, 250);

//Time
ctx.font = "23px Arial";
ctx.fillStyle = '28d1fa';
ctx.fillText(time, 175, 280);

var dataUrl = canvas.toDataUrl();

document.getElementById('myImage').src = dataUrl;

}

setInterval(renderTime, 40);

</script>

</body>
</html>

有人可以帮助我吗?

最佳答案

更改此行:

var time = today.toLocaleTimeString();
gradient = ctx.createRadioGradient(250, 250, 5, 250, 250, 300);
var dataUrl = canvas.toDataUrl();

对此:

var time = now.toLocaleTimeString();
gradient = ctx.createRadialGradient(250, 250, 5, 250, 250, 300);
var dataUrl = canvas.toDataURL();

这应该会让您进入屏幕。我建议您使用 Chrome 的开发人员控制台来查看所有 JavaScript 错误。

关于javascript - 用 html canvas 构建一个时钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40225966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com