<script type="text/javascript">
window.onload = function () {
/** @type {HTMLCanvasElement} */
var flag = 0;
var scale = 0;
var flagScale = 0;
//1.获取画布
var canvas = document.querySelector('#test');
if (canvas.getContext) {
//2.获取画笔
var ctx = canvas.getContext('2d');
setInterval(function(){
ctx.clearRect(0,0,canvas.width,canvas.height);
move();
}, 1000);
function move() {
ctx.save();
//初始化圆盘样式
ctx.lineWidth = 8;
ctx.strokeStyle = 'black';
ctx.lineCap = 'round'
ctx.translate(200, 200);
ctx.rotate(-90 * Math.PI / 180);
ctx.beginPath();
//外层空心圆盘
ctx.save();
ctx.lineWidth = 14;
ctx.strokeStyle = '#325FA2';
ctx.beginPath();
ctx.arc(0, 0, 140, 0, 360 * Math.PI / 180)
ctx.stroke();
ctx.restore();
//时针刻度
ctx.save();
for (var i = 0; i < 12; i++) {
ctx.rotate(30 * Math.PI / 180);//canvas中rotate的变化是累加的
ctx.beginPath();
ctx.moveTo(100, 0);
ctx.lineTo(120, 0);
ctx.stroke();
}
ctx.restore();
//分针刻度
ctx.save();
ctx.lineWidth = 4;
for (var i = 0; i < 60; i++) {
if (i % 5 != 0) {
ctx.beginPath();
ctx.moveTo(117, 0);
ctx.lineTo(120, 0);
ctx.stroke();
}
ctx.rotate(6 * Math.PI / 180);
}
ctx.restore();
//时针 分针 秒针 表座
var date = new Date();
var s = date.getSeconds();
var m = date.getMinutes() + s / 60;
var h = date.getHours() + m / 60;
h = h > 12 ? h - 12 : h;
//时针
ctx.save();
ctx.lineWidth = 14;
ctx.beginPath();
ctx.rotate(h * 30 * Math.PI / 180)
ctx.moveTo(-20, 0);
ctx.lineTo(80, 0);
ctx.stroke();
ctx.restore();
//分针
ctx.save();
ctx.lineWidth = 10;
ctx.beginPath();
ctx.rotate(m * 6 * Math.PI / 180)
ctx.moveTo(-28, 0);
ctx.lineTo(112, 0);
ctx.stroke();
ctx.restore();
//秒针
ctx.save();
ctx.strokeStyle = '#D40000';
ctx.lineWidth = 6;
ctx.fillStyle = '#D40000';
ctx.beginPath();
ctx.rotate(s * 6 * Math.PI / 180);
ctx.moveTo(-30, 0);
ctx.lineTo(83, 0);
ctx.stroke();
//表座
ctx.beginPath();
ctx.arc(0, 0, 10, 0, 360 * Math.PI / 180);
ctx.fill();
//表头
ctx.beginPath();
ctx.arc(96, 0, 10, 0, 360 * Math.PI / 180)
ctx.stroke()
ctx.restore();
ctx.restore();
}
}
}
</script>
canvas-钟表实例-完整
最新推荐文章于 2023-10-26 08:47:56 发布