本帖最后由 lzh68575536 于 2022-11-22 13:01 编辑
专门用来教小朋友认识时钟
[HTML] 纯文本查看 复制代码 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>HTML5time</title>
<!--本地jQuery-->
<script src="./jquery.min.js"></script>
<style>
.clocks {
height: 900px;
margin: 25px auto;
position: relative;
width: 900px;
}
</style>
</head>
<body>
<header>
</header>
<div class="clocks">
<canvas id="canvas" width="800" height="800"></canvas>
</div>
</body>
<script>
//初始化参数
var canvas, ctx;
var clockRadius = 250;
var clockImage;
//清空画布
function clear() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
//画图
function drawScene(hours = 0,minutes = 0,seconds = 0) {
clockImage = new Image();
clockImage.src = "./time.png";//本地图片
clockImage.onload = function(){ctx.drawImage(clockImage, 50, 50, 700, 700)};
clear();
//获取时间
var date = new Date();
var hours = hours>0?hours:date.getHours();
var minutes = minutes>0?minutes:date.getMinutes();
var seconds = seconds>0?seconds:date.getSeconds();
hours = hours > 12 ? hours - 12 : hours;
var hour = hours + minutes / 60;
var minute = minutes ;
ctx.save();
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.beginPath();
ctx.font = '36px Arial';
ctx.fillStyle = '#000';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
//标注小时
for (var n = 1; n <= 12; n++) {
var theta = (n - 3) * (Math.PI * 2) / 12;
var x = clockRadius * 1 * Math.cos(theta);
var y = clockRadius * 1 * Math.sin(theta);
ctx.fillText(n, x, y);
}
//标注分钟
for (var n = 1; n <= 60; n++) {
var theta = (n-15) * (Math.PI * 2) / 60;
var x = clockRadius * 1.4 * Math.cos(theta);
var y = clockRadius * 1.4 * Math.sin(theta);
ctx.fillStyle = 'red';
ctx.font = "20px sans-serif"
ctx.fillText(n, x, y);
}
//画时钟
ctx.save();
var theta = (hour - 3) * 2 * Math.PI / 12;
ctx.rotate(theta);
ctx.beginPath();
ctx.moveTo(-15, -5);
ctx.lineTo(-15, 5);
ctx.lineTo(clockRadius * 0.7, 1);
ctx.lineTo(clockRadius * 0.7, -1);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.restore();
//画分钟
ctx.save();
var theta = (minute - 15) * 2 * Math.PI / 60;
ctx.rotate(theta);
ctx.beginPath();
ctx.moveTo(-15, -4);
ctx.lineTo(-15, 4);
ctx.lineTo(clockRadius * 1, 1);
ctx.lineTo(clockRadius * 1, -1);
ctx.fillStyle = 'red';
ctx.fill();
ctx.restore();
//画秒钟
ctx.save();
var theta = (seconds - 15) * 2 * Math.PI / 60;
ctx.rotate(theta);
ctx.beginPath();
ctx.moveTo(-15, -3);
ctx.lineTo(-15, 3);
ctx.lineTo(clockRadius * 1.2, 1);
ctx.lineTo(clockRadius * 1.2, -1);
ctx.fillStyle = '#D5D52B';
ctx.fill();
ctx.restore();
ctx.restore();
}
$(function(){
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
//setInterval(drawScene, 1000);//当前时间
drawScene(12,1,30);//手动调整时间
});
</script>
</html>
钟表背景图片
效果图
|